@vibe-cafe/vibe-usage 0.10.31 → 0.10.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -50,7 +50,7 @@ npx @vibe-cafe/vibe-usage reset # Delete all data and re-upload from loca
50
50
  npx @vibe-cafe/vibe-usage reset --local # Delete this host's data only and re-upload (`--host` remains a legacy alias)
51
51
  npx @vibe-cafe/vibe-usage skill # Install skill for AI coding assistants
52
52
  npx @vibe-cafe/vibe-usage skill --remove # Remove installed skills
53
- npx @vibe-cafe/vibe-usage status # Show config & detected tools
53
+ npx @vibe-cafe/vibe-usage status # Config, detected tools, and what each tool has uploaded so far
54
54
  npx @vibe-cafe/vibe-usage help --all # Full help (plain `help` shows the short version)
55
55
  ```
56
56
 
@@ -76,7 +76,7 @@ npx @vibe-cafe/vibe-usage help --all # Full help (plain `help` shows the short
76
76
  | Oh My Pi | `~/.omp/agent/sessions/`, `~/.omp/profiles/*/agent/sessions/`, and `$XDG_DATA_HOME/omp/{sessions,profiles/*/sessions}`; recognizes OMP's `$PI_CODING_AGENT_DIR`, current v3 title slots and path/hashed session directories, deduplicates copied records, includes cache writes in input, and splits reasoning from OMP's inclusive output count |
77
77
  | pi | `~/.pi/agent/sessions/` or `$PI_CODING_AGENT_DIR/sessions/`, plus the session directory Pi itself was pointed at via `PI_CODING_AGENT_SESSION_DIR` or `sessionDir` in `~/.pi/agent/settings.json`, plus explicitly added `pi-coding-agent` roots for stores only reachable through `pi --session <file>` (fixture/relocation override: `VIBE_USAGE_PI_SESSION_DIRS`). Cache writes are included in input usage; reasoning is read from Pi's `usage.reasoning` (legacy `usage.reasoningTokens` still accepted) and split out of the inclusive output total |
78
78
  | Qwen Code | `~/.qwen/tmp/` |
79
- | Kimi Code | Current `~/.kimi-code/sessions/wd_<slug>_<hash>/session_<id>/agents/<agent>/wire.jsonl` (`usage.record` deltas, including retry/compaction scope and cache creation; main/subagent wires form one session), data root resolved via `$KIMI_CODE_HOME` like the CLI itself, with project names from `session_index.jsonl`; legacy `~/.kimi/sessions/` is parsed alongside (`kimi migrate` never carries usage over, so both stores are always merged) |
79
+ | Kimi Code | Current `<home>/sessions/wd_<slug>_<hash>/session_<id>/agents/<agent>/wire.jsonl` (`usage.record` deltas, including retry/compaction scope and cache creation; main/subagent wires form one session), with project names from `session_index.jsonl`. Every home with that layout is scanned: the CLI home (`$KIMI_CODE_HOME`, else `~/.kimi-code`) plus the Kimi Work desktop app's embedded runtime home (`<Electron userData>/kimi-desktop/daimon-share/daimon/runtime/kimi-code/home`), which the app never writes into the CLI home; legacy `~/.kimi/sessions/` is parsed alongside (`kimi migrate` never carries usage over, so both stores are always merged) |
80
80
  | MiniMax Code (mcode) | `$MCODE_HOME/v2/sqlite/runtime-state.sqlite` (default `~/.minimax/v2/sqlite/runtime-state.sqlite`; fixture override: `VIBE_USAGE_MCODE_DB`). Reads only allow-listed token ledger fields and session workspace/project paths, uses basename-only projects, folds cache writes into input, keeps cache reads and reasoning separate, and never selects raw/message JSON payloads. WAL/lock reads use a disposable snapshot; malformed or incompatible databases are skipped to preserve incremental state. |
81
81
  | MiMoCode | `$MIMOCODE_HOME/data/mimocode.db`, `$XDG_DATA_HOME/mimocode/mimocode.db`, or `~/.local/share/mimocode/mimocode.db` (SQLite; exact input, output, reasoning, and cache-read tokens from assistant messages; honors `MIMOCODE_DB`; cache-write tokens are included in input usage) |
82
82
  | Amp | `~/.local/share/amp/threads/`; cache-creation tokens are included in input usage |
@@ -84,12 +84,12 @@ npx @vibe-cafe/vibe-usage help --all # Full help (plain `help` shows the short
84
84
  | DeepSeek Harness | `$DSH_HOME/sessions/` (default `~/.dsh`, fixture/relocation override: `VIBE_USAGE_DSH_SESSIONS`). Reads V0–V3 logs, including `session.v3.jsonl.zstd` from DSH `0.1.5-alpha.2`, with multi-frame Zstandard support (Node ≥ 22.15 built-in, `zstd` CLI fallback) and plain JSONL support. Each session uses its highest `session[.vN].jsonl[.zstd]` generation once, so frozen pre-migration logs are not double-counted. Usage comes from `assistant/message`: cache writes join uncached input, cache reads remain separate, and reasoning is split out of inclusive output. Fork history uses V0/V1 `seedLength` or V2/V3's last `session/end-seed` tagged `inherited: true`, and is skipped only when the parent copy confirms it; missing parents retain the sole local history. Unknown versions warn and protect sync state. |
85
85
  | Hermes (CLI / Desktop) | `<home>/state.db` + `<home>/profiles/<name>/state.db` (SQLite, multi-profile). Home: `$HERMES_HOME`, otherwise `~/.hermes` on macOS/Linux or `%LOCALAPPDATA%\hermes` on Windows (falls back to an existing `~/.hermes` only when the Windows native root is absent). Cache writes join input; reasoning is separated from inclusive output. Usage is currently a cumulative session total attributed to session start: a session spanning several days does **not** yet provide an accurate daily breakdown. |
86
86
  | Kiro | Kiro CLI native event streams `~/.kiro/sessions/cli/*.jsonl` (estimated tokens from message text: input = prompt + tool results, output = reply + tool calls, reasoning = thinking, cacheRead = re-sent context; thinking-block signatures excluded). Falls back to `~/Library/Application Support/kiro-cli/data.sqlite3` / `~/.local/share/kiro-cli/data.sqlite3` + optional `~/.kiro_sessions/*.json` archives, then IDE `q-client.log` whole-credit deltas as `kiro-credits` (floored cumulative diff — the server stores token counts as bigint); legacy IDE `dev_data/devdata.sqlite` token telemetry is opt-in with `VIBE_USAGE_KIRO_LEGACY_TOKENS=1` |
87
- | Cline | Current CLI/SDK `~/.cline/data/sessions/*/*.messages.json` plus legacy `~/.cline/{,data/}state/taskHistory.json` and editor extension stores. Honors `CLINE_DIR`, `CLINE_DATA_DIR`, and `CLINE_SESSION_DATA_DIR`; copied history is deduplicated |
87
+ | Cline (CLI / SDK / Desktop app) | All variants write the same `~/.cline/data/sessions/*/*.messages.json` per-call metrics (the desktop app's manifest says `source: "desktop"`; its Electron userData holds only WebView caches), plus legacy `~/.cline/{,data/}state/taskHistory.json` and editor extension stores. Honors `CLINE_DIR`, `CLINE_DATA_DIR`, and `CLINE_SESSION_DATA_DIR`; copied history is deduplicated |
88
88
  | Roo Code | `<host>/User/globalStorage/rooveterinaryinc.roo-cline/{tasks/_index.json,tasks/<id>/{history_item,ui_messages}.json}` (walks all VSCode-fork hosts) |
89
89
  | Trae CLI | macOS: `~/Library/Caches/trae-cli/sessions/`; Windows: `%LOCALAPPDATA%/trae-cli/cache/sessions/`; Linux: `~/.cache/trae-cli/sessions/` (CLI telemetry only; Trae IDE/Trae Work chats are not supported). Token usage is summed per unique LLM call (`model.stream.eino`, plus `model.generate` failovers); nested duplicate spans that share a session `traceID` are not max-merged. `traces.jsonl` / `events.jsonl` are streamed line-by-line so a multi-hundred-MB events file cannot hit Node's string-length limit. |
90
90
  | Antigravity | Scans App 2.0 `~/.gemini/antigravity/conversations/`, `agy` CLI `~/.gemini/antigravity-cli/conversations/`, and standalone IDE `~/.gemini/antigravity-ide/conversations/`. `.db` stores, including the same paths below explicitly added alternate Homes, are parsed offline (tokens, model, project, sessions). When Gemini blobs omit `chatStartMetadata.createdAt` or `modelDisplayName`, timestamps fall back to `steps.metadata` and model names to `responseModel`. `.pb` history in the default stores requires the corresponding App/IDE language server to be running; when several servers are open, the parser tries the others for unreadable conversations. Unavailable legacy history produces a warning and preserves prior sync state. |
91
91
  | WorkBuddy | Current releases: `~/.workbuddy-ai/projects/**/*.jsonl`; legacy releases: `~/.workbuddy/projects/**/*.jsonl` (fixture/relocation override: `VIBE_USAGE_WORKBUDDY_DIRS`). Reads usage-bearing completed assistant and `function_call` records, using the routed model identifier exposed as `providerData.requestModelId`. Splits cache reads and reasoning from inclusive input/output totals, deduplicates copied record IDs, and extracts local session timing without uploading message content. |
92
- | ZCode | `~/.zcode/cli/db/db.sqlite` (SQLite; reads the `message` table for per-message tokens, model, and project `cwd`/`root`, joined to `session.directory`) |
92
+ | ZCode | `~/.zcode/cli/db/db.sqlite` (SQLite; reads the `message` table for per-message tokens, model, and project `cwd`/`root`, joined to `session.directory`; fixture/relocation override: `VIBE_USAGE_ZCODE_DB`) |
93
93
  | Qoder | International edition (qoder.com). IDE store `~/Library/Application Support/Qoder/SharedClientCache/cache/db/local.db` (Windows `%APPDATA%\Qoder`, Linux `~/.config/Qoder`; honors `QODER_HOME`, fixture override `VIBE_USAGE_QODER_DB`) gives real tokens from `chat_message.token_info` (prompt includes cached; split out) with `model_key` usually a routing tier, reported as `qoder-auto` / `qoder-ultimate` / … so it never collides with a priced model id; message content is never selected, and lock/schema failures fall back to a snapshot or `skipped`. CLI + desktop app transcripts `~/.qoder/projects/**/*.jsonl` (honors `QODER_CONFIG_DIR`, fixture override `VIBE_USAGE_QODER_PROJECTS`; sub-agents under `<session>/subagents/`) are credit-billed with every token field at 0, so they contribute sessions only — credits are account funding and are not collected |
94
94
  | Qoder CN | China edition (qoder.com.cn, separate account). Same two shapes under `~/Library/Application Support/QoderCN/SharedClientCache/cache/db/local.db` (`QODER_CN_HOME` / `VIBE_USAGE_QODER_CN_DB`) and `~/.qoder-cn/projects/` (`QODERCN_CONFIG_DIR` / `VIBE_USAGE_QODER_CN_PROJECTS`); reported as source `qoder-cn` |
95
95
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibe-cafe/vibe-usage",
3
- "version": "0.10.31",
3
+ "version": "0.10.32",
4
4
  "description": "Track your AI coding tool token usage and sync to vibecafe.ai",
5
5
  "type": "module",
6
6
  "scripts": {
package/src/index.js CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  validateExtraRoot,
10
10
  } from './extra-roots.js';
11
11
  import { dim as dimText, failure, hint, smallHeader, warn } from './output.js';
12
+ import { loadState } from './state.js';
12
13
  import { fetchAccount } from './api.js';
13
14
 
14
15
  function printSmallHeader() {
@@ -17,6 +18,25 @@ function printSmallHeader() {
17
18
  console.log();
18
19
  }
19
20
 
21
+ /**
22
+ * Per-source counts of everything `state.json` records as uploaded. Keys are
23
+ * `${source}|…` (see state.js), so the source is the first segment.
24
+ */
25
+ function uploadedItemCounts(state) {
26
+ const countBySource = keys => {
27
+ const counts = new Map();
28
+ for (const key of keys) {
29
+ const source = key.split('|')[0];
30
+ counts.set(source, (counts.get(source) || 0) + 1);
31
+ }
32
+ return counts;
33
+ };
34
+ return {
35
+ buckets: countBySource(Object.keys(state.buckets || {})),
36
+ sessions: countBySource(Object.keys(state.sessions || {})),
37
+ };
38
+ }
39
+
20
40
  async function showStatus() {
21
41
  const config = loadConfig();
22
42
  console.log('\nvibe-usage status\n');
@@ -49,8 +69,21 @@ async function showStatus() {
49
69
  if (detected.length === 0) {
50
70
  console.log(' (none)\n');
51
71
  } else {
72
+ // "installed" alone cannot separate "syncing fine" from "never uploaded":
73
+ // a tool whose data dir exists but whose buckets never reached the server
74
+ // reads exactly like a healthy one, which is how a stale bundled CLI stayed
75
+ // invisible (issue #100). state.json is the only local record of what was
76
+ // actually uploaded, so count it per source.
77
+ const uploaded = uploadedItemCounts(loadState());
52
78
  for (const tool of detected) {
53
- console.log(` ${tool.name}`);
79
+ const buckets = uploaded.buckets.get(tool.id) || 0;
80
+ const sessions = uploaded.sessions.get(tool.id) || 0;
81
+ if (buckets || sessions) {
82
+ console.log(` ${tool.name} · 已上传 ${buckets} buckets / ${sessions} sessions`);
83
+ } else {
84
+ console.log(` ${tool.name} · 尚未上传过数据`);
85
+ console.log(dimText(' 本机检测到数据,但本地没有这条工具的上传记录:运行 `npx @vibe-cafe/vibe-usage` 同步'));
86
+ }
54
87
  }
55
88
  console.log();
56
89
  }
@@ -0,0 +1,63 @@
1
+ import { existsSync, realpathSync } from 'node:fs';
2
+ import { join, posix, win32 } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+
5
+ // Root discovery for Kimi Code. The CLI keeps one data home, and the Kimi Work
6
+ // desktop app runs an embedded Kimi Code runtime whose home has the CLI's exact
7
+ // layout (issue #85), so both homes are scanned additively.
8
+
9
+ // Kimi Work's embedded runtime home, relative to the app's Electron userData.
10
+ const DAIMON_RUNTIME = ['daimon-share', 'daimon', 'runtime', 'kimi-code', 'home'];
11
+
12
+ /** Kimi Work's embedded Kimi Code home for this platform. */
13
+ export function kimiWorkCodeHome(env = process.env, platform = process.platform, home = homedir()) {
14
+ const pathImpl = platform === 'win32' ? win32 : posix;
15
+ const userData = platform === 'darwin'
16
+ ? pathImpl.join(home, 'Library', 'Application Support')
17
+ : platform === 'win32'
18
+ ? (env.APPDATA?.trim() || pathImpl.join(home, 'AppData', 'Roaming'))
19
+ : (env.XDG_CONFIG_HOME?.trim() || pathImpl.join(home, '.config'));
20
+ return pathImpl.join(userData, 'kimi-desktop', ...DAIMON_RUNTIME);
21
+ }
22
+
23
+ // Two roots can name the same directory (symlinks, a relocated home that still
24
+ // resolves to the same store); scanning both would double-count every record.
25
+ function uniquePaths(paths) {
26
+ const seen = new Set();
27
+ const result = [];
28
+ for (const path of paths) {
29
+ let key = path;
30
+ try { key = realpathSync(path); } catch { /* not created yet — compare as given */ }
31
+ if (seen.has(key)) continue;
32
+ seen.add(key);
33
+ result.push(path);
34
+ }
35
+ return result;
36
+ }
37
+
38
+ /**
39
+ * Kimi Code data homes to scan, primary first.
40
+ *
41
+ * `VIBE_USAGE_KIMI_CODE_DIR` (test/relocation hook) replaces discovery entirely,
42
+ * so a fixture never picks up the machine's real stores. Otherwise the CLI home
43
+ * — `$KIMI_CODE_HOME` when set, exactly like the CLI itself — is scanned
44
+ * alongside the Kimi Work desktop home; the desktop app never writes into the
45
+ * CLI home, so the two stores are independent.
46
+ */
47
+ export function resolveKimiCodeRoots(env = process.env, platform = process.platform, home = homedir()) {
48
+ const override = env.VIBE_USAGE_KIMI_CODE_DIR?.trim();
49
+ if (override) return [override];
50
+ const pathImpl = platform === 'win32' ? win32 : posix;
51
+ return uniquePaths([
52
+ env.KIMI_CODE_HOME?.trim() || pathImpl.join(home, '.kimi-code'),
53
+ kimiWorkCodeHome(env, platform, home),
54
+ ]);
55
+ }
56
+
57
+ /** Existing Kimi Code session stores, for tool detection (`status`). */
58
+ export function findKimiCodeDataDirs() {
59
+ return uniquePaths([
60
+ ...resolveKimiCodeRoots().map(root => join(root, 'sessions')),
61
+ join(homedir(), '.kimi', 'sessions'), // legacy store, always parsed alongside
62
+ ]).filter(existsSync);
63
+ }
@@ -5,12 +5,30 @@ import { projectFromCwd, toCount } from './fs-utils.js';
5
5
  // Verified with the shipped cline 3.0.61 / @cline/core 0.0.82. SQLite is only
6
6
  // the session index: per-call accounting lives in version-1 messages artifacts.
7
7
  // Read canonical artifacts, not DB prompt/metadata columns or provider settings.
8
- export function readClineSdk(sessionDirs, onWarning) {
8
+ //
9
+ // Two failure sizes, because they mean different things (see AGENTS.md):
10
+ // a *format* mismatch means the store moved on and any number we produce would
11
+ // be wrong, so the caller must skip the source and keep its previous upload
12
+ // state; an *IO* failure on one artifact (the desktop app rewrites these files
13
+ // in place, so half-written JSON is normal) drops only that artifact, while the
14
+ // rest of the store still syncs. Transient losses re-upload on the next sync.
15
+ function unsupported(message) {
16
+ const error = new Error(message);
17
+ error.clineUnsupported = true;
18
+ return error;
19
+ }
20
+
21
+ export function readClineSdk(sessionDirs, { onWarning = () => {}, onFatal = () => {} } = {}) {
9
22
  const copies = [];
10
23
  for (const dir of sessionDirs) {
11
24
  let children;
12
25
  try { children = readdirSync(dir, { withFileTypes: true }); }
13
- catch (err) { onWarning(`cline: 无法读取会话目录 ${dir}: ${err.message}`); continue; }
26
+ catch (err) {
27
+ // Cannot enumerate this root: the snapshot may be missing sessions we
28
+ // could not even list, so the whole source is unsafe this run.
29
+ onFatal(`cline: 无法读取会话目录 ${dir}: ${err.message}`);
30
+ continue;
31
+ }
14
32
  for (const child of children) {
15
33
  if (!child.isDirectory()) continue;
16
34
  const sessionDir = join(dir, child.name);
@@ -21,10 +39,11 @@ export function readClineSdk(sessionDirs, onWarning) {
21
39
  if (!files.length) continue;
22
40
  manifest = JSON.parse(readFileSync(join(sessionDir, `${child.name}.json`), 'utf8'));
23
41
  if (manifest?.version !== 1 || manifest.session_id !== child.name) {
24
- throw new Error('unsupported or inconsistent Cline session manifest');
42
+ throw unsupported('unsupported or inconsistent Cline session manifest');
25
43
  }
26
44
  } catch (err) {
27
- onWarning(`cline: 无法读取会话目录 ${sessionDir}: ${err.message}`);
45
+ if (err?.clineUnsupported) onFatal(`cline: 不支持或不一致的会话清单 ${sessionDir}: ${err.message}`);
46
+ else onWarning(`cline: 跳过无法读取的会话目录 ${sessionDir}: ${err.message}`);
28
47
  continue;
29
48
  }
30
49
  for (const file of files) {
@@ -34,7 +53,7 @@ export function readClineSdk(sessionDirs, onWarning) {
34
53
  if (payload?.version !== 1 || !Array.isArray(payload.messages)
35
54
  || typeof payload.sessionId !== 'string'
36
55
  || (payload.sessionId !== child.name && payload.origin?.parentThreadId !== child.name)) {
37
- throw new Error('unsupported or inconsistent Cline session artifact');
56
+ throw unsupported('unsupported or inconsistent Cline session artifact');
38
57
  }
39
58
  const project = projectFromCwd(manifest.workspace_root || manifest.cwd);
40
59
  // Reduce immediately to accounting/timing metadata. No prompt, response,
@@ -68,7 +87,8 @@ export function readClineSdk(sessionDirs, onWarning) {
68
87
  // shared history to the earliest original session deterministically.
69
88
  started: Date.parse(manifest.started_at) || 0, messagesPath });
70
89
  } catch (err) {
71
- onWarning(`cline: 无法读取会话 ${messagesPath}: ${err.message}`);
90
+ if (err?.clineUnsupported) onFatal(`cline: 不支持或不一致的会话文件 ${messagesPath}: ${err.message}`);
91
+ else onWarning(`cline: 跳过无法读取的会话文件 ${messagesPath}: ${err.message}`);
72
92
  }
73
93
  }
74
94
  }
@@ -7,8 +7,13 @@ import { readClineSdk } from './cline-sdk.js';
7
7
 
8
8
  export async function parse() {
9
9
  const warnings = [];
10
+ // Format drift or an unreadable root means we cannot describe the store:
11
+ // skip the source so its previous upload state survives. A single unreadable
12
+ // artifact only drops that artifact (it re-uploads on the next sync).
13
+ let fatal = false;
10
14
  const onWarning = message => warnings.push(message);
11
- const { legacyRoots: extDirs, sdkSessionDirs } = findClineStores({ onWarning });
15
+ const onFatal = message => { fatal = true; warnings.push(message); };
16
+ const { legacyRoots: extDirs, sdkSessionDirs } = findClineStores({ onWarning: onFatal });
12
17
 
13
18
  const entries = [];
14
19
  const events = [];
@@ -90,8 +95,9 @@ export async function parse() {
90
95
  }
91
96
  }
92
97
 
93
- const sdk = readClineSdk(sdkSessionDirs, onWarning);
94
- if (warnings.length) return { buckets: [], sessions: [], skipped: true, warnings };
98
+ const sdk = readClineSdk(sdkSessionDirs, { onWarning, onFatal });
99
+ if (fatal) return { buckets: [], sessions: [], skipped: true, warnings };
95
100
  return { buckets: aggregateToBuckets([...entries, ...sdk.entries]),
96
- sessions: extractSessions([...events, ...sdk.events]) };
101
+ sessions: extractSessions([...events, ...sdk.events]),
102
+ warnings };
97
103
  }
@@ -1,8 +1,9 @@
1
- import { readdirSync, readFileSync, existsSync } from 'node:fs';
1
+ import { readdirSync, readFileSync, existsSync, realpathSync } from 'node:fs';
2
2
  import { join, basename } from 'node:path';
3
3
  import { homedir } from 'node:os';
4
4
  import { createHash } from 'node:crypto';
5
5
  import { aggregateToBuckets, extractSessions } from './aggregate.js';
6
+ import { resolveKimiCodeRoots } from '../kimi-roots.js';
6
7
 
7
8
  /**
8
9
  * Kimi Code CLI parser. MoonshotAI/kimi-cli (a.k.a. "Kimi Code").
@@ -19,8 +20,13 @@ import { aggregateToBuckets, extractSessions } from './aggregate.js';
19
20
  * sum to the session total. The model name rides on each record — no config
20
21
  * lookup needed. User turns are `turn.prompt` with origin.kind === "user".
21
22
  * The real working directory per session is recorded in
22
- * ~/.kimi-code/session_index.jsonl -> {sessionId, sessionDir, workDir}
23
+ * <home>/session_index.jsonl -> {sessionId, sessionDir, workDir}
23
24
  * which gives an accurate project name (last path component of workDir).
25
+ * Several homes share this layout and are all scanned (see kimi-roots.js):
26
+ * the CLI home ($KIMI_CODE_HOME, else ~/.kimi-code) and the Kimi Work
27
+ * desktop app's embedded runtime home. The desktop app never writes into the
28
+ * CLI home, so the stores are independent and merging them cannot
29
+ * double-count.
24
30
  *
25
31
  * 2. Legacy ("~/.kimi", protocol 1.1 / 1.9). Sessions live at
26
32
  * ~/.kimi/sessions/<md5(workdir)>/<session-id>/wire.jsonl
@@ -39,15 +45,12 @@ import { aggregateToBuckets, extractSessions } from './aggregate.js';
39
45
  // Current format: ~/.kimi-code
40
46
  // ---------------------------------------------------------------------------
41
47
 
42
- // VIBE_USAGE_KIMI_CODE_DIR overrides the root (test hook). Otherwise resolve
43
- // the data root the same way the CLI itself does: $KIMI_CODE_HOME, then
44
- // ~/.kimi-code. Ignoring KIMI_CODE_HOME means users with a custom home get
45
- // zero usage parsed.
46
- const KIMI_CODE_DIR = process.env.VIBE_USAGE_KIMI_CODE_DIR?.trim()
47
- || process.env.KIMI_CODE_HOME?.trim()
48
- || join(homedir(), '.kimi-code');
49
- const KIMI_CODE_SESSIONS_DIR = join(KIMI_CODE_DIR, 'sessions');
50
- const KIMI_CODE_SESSION_INDEX = join(KIMI_CODE_DIR, 'session_index.jsonl');
48
+ // VIBE_USAGE_KIMI_CODE_DIR overrides the root (test hook). Otherwise every root
49
+ // from kimi-roots.js is scanned — the CLI home resolved the same way the CLI
50
+ // itself resolves it ($KIMI_CODE_HOME, then ~/.kimi-code) plus the Kimi Work
51
+ // desktop app's embedded runtime home (issue #85), which uses this exact
52
+ // layout. Ignoring KIMI_CODE_HOME means users with a custom home get zero usage
53
+ // parsed; ignoring the desktop home means Kimi Work users get zero usage parsed.
51
54
 
52
55
  function projectNameFromPath(path) {
53
56
  if (typeof path !== 'string' || !path) return null;
@@ -55,17 +58,17 @@ function projectNameFromPath(path) {
55
58
  }
56
59
 
57
60
  /**
58
- * Map each session directory (absolute path) to a project name, read from
59
- * ~/.kimi-code/session_index.jsonl. Falls back gracefully if the file is
60
- * missing or malformed — callers default to the wd_ bucket name.
61
+ * Map each session directory (absolute path) to a project name, read from the
62
+ * home's session_index.jsonl. Falls back gracefully if the file is missing or
63
+ * malformed — callers default to the wd_ bucket name.
61
64
  */
62
- function loadSessionIndex() {
65
+ function loadSessionIndex(indexPath) {
63
66
  const map = new Map();
64
- if (!existsSync(KIMI_CODE_SESSION_INDEX)) return map;
67
+ if (!existsSync(indexPath)) return map;
65
68
 
66
69
  let content;
67
70
  try {
68
- content = readFileSync(KIMI_CODE_SESSION_INDEX, 'utf-8');
71
+ content = readFileSync(indexPath, 'utf-8');
69
72
  } catch {
70
73
  return map;
71
74
  }
@@ -141,15 +144,35 @@ function findKimiCodeWireFiles(baseDir) {
141
144
  return results;
142
145
  }
143
146
 
147
+ /**
148
+ * Every wire file to parse, with its project name, across all Kimi Code homes.
149
+ * Two roots can resolve to the same store (symlink, relocated home), so the
150
+ * same physical wire file is returned once.
151
+ */
152
+ function findKimiCodeWireFilesInAllRoots() {
153
+ const results = [];
154
+ const seen = new Set();
155
+ for (const root of resolveKimiCodeRoots()) {
156
+ const sessionIndex = loadSessionIndex(join(root, 'session_index.jsonl'));
157
+ for (const { wireFile, sessionDir, bucketProject } of findKimiCodeWireFiles(join(root, 'sessions'))) {
158
+ let identity = wireFile;
159
+ try { identity = realpathSync(wireFile); } catch { /* keep the literal path */ }
160
+ if (seen.has(identity)) continue;
161
+ seen.add(identity);
162
+ results.push({ wireFile, sessionDir, project: sessionIndex.get(sessionDir) || bucketProject || 'unknown' });
163
+ }
164
+ }
165
+ return results;
166
+ }
167
+
144
168
  function parseKimiCode() {
145
- const wireFiles = findKimiCodeWireFiles(KIMI_CODE_SESSIONS_DIR);
169
+ const wireFiles = findKimiCodeWireFilesInAllRoots();
146
170
  if (wireFiles.length === 0) return null;
147
171
 
148
- const sessionIndex = loadSessionIndex();
149
172
  const entries = [];
150
173
  const sessionEvents = [];
151
174
 
152
- for (const { wireFile, sessionDir, bucketProject } of wireFiles) {
175
+ for (const { wireFile, sessionDir, project } of wireFiles) {
153
176
  let content;
154
177
  try {
155
178
  content = readFileSync(wireFile, 'utf-8');
@@ -157,8 +180,6 @@ function parseKimiCode() {
157
180
  continue;
158
181
  }
159
182
 
160
- const project = sessionIndex.get(sessionDir) || bucketProject || 'unknown';
161
-
162
183
  for (const line of content.split('\n')) {
163
184
  if (!line.trim()) continue;
164
185
  let evt;
@@ -1,8 +1,8 @@
1
1
  import { existsSync } from 'node:fs';
2
- import { join, basename } from 'node:path';
3
- import { homedir } from 'node:os';
2
+ import { basename } from 'node:path';
4
3
  import { aggregateToBuckets, extractSessions } from './aggregate.js';
5
4
  import { queryDbJson, sqliteUnavailableError, isSqliteUnavailableError } from './sqlite.js';
5
+ import { getZcodeDbPath } from '../tools.js';
6
6
 
7
7
  // ZCode (z.ai / Zhipu's coding agent) stores everything in a SQLite database
8
8
  // at ~/.zcode/cli/db/db.sqlite. The `message` table is the canonical source:
@@ -11,7 +11,9 @@ import { queryDbJson, sqliteUnavailableError, isSqliteUnavailableError } from '.
11
11
  // than the parallel `model_usage` ledger because `message` gives us BOTH session
12
12
  // timing (user + assistant rows) and token usage in one pass, with the project
13
13
  // path attached to each message.
14
- const DB_PATH = join(homedir(), '.zcode', 'cli', 'db', 'db.sqlite');
14
+ export function resolveZcodeDbPath(env = process.env) {
15
+ return getZcodeDbPath(env);
16
+ }
15
17
 
16
18
  /**
17
19
  * Project name from a ZCode message's path. ZCode records both `cwd` and `root`;
@@ -26,15 +28,20 @@ function projectName(root, cwd, sessionDir) {
26
28
  }
27
29
 
28
30
  export async function parse() {
29
- if (!existsSync(DB_PATH)) return { buckets: [], sessions: [] };
31
+ const dbPath = resolveZcodeDbPath();
32
+ if (!existsSync(dbPath)) return { buckets: [], sessions: [] };
30
33
 
31
34
  // Join each message to its session so we can fall back to the session's
32
35
  // directory when an individual message has no path (older rows, lite agents).
36
+ // ZCode renamed the assistant message's model keys from `modelID` /
37
+ // `providerID` to `modelId` / `providerId`; read both spellings so neither
38
+ // build reports every bucket as `unknown`.
33
39
  const query = `SELECT
34
40
  m.session_id AS sessionId,
35
41
  m.time_created AS created,
36
42
  json_extract(m.data, '$.role') AS role,
37
43
  json_extract(m.data, '$.modelID') AS modelID,
44
+ json_extract(m.data, '$.modelId') AS modelId,
38
45
  json_extract(m.data, '$.tokens') AS tokens,
39
46
  json_extract(m.data, '$.path.root') AS pathRoot,
40
47
  json_extract(m.data, '$.path.cwd') AS pathCwd,
@@ -44,7 +51,7 @@ export async function parse() {
44
51
 
45
52
  let rows;
46
53
  try {
47
- rows = queryDbJson(DB_PATH, query);
54
+ rows = queryDbJson(dbPath, query);
48
55
  } catch (err) {
49
56
  if (isSqliteUnavailableError(err)) throw sqliteUnavailableError('ZCode');
50
57
  throw err;
@@ -88,7 +95,7 @@ export async function parse() {
88
95
 
89
96
  entries.push({
90
97
  source: 'zcode',
91
- model: row.modelID || 'unknown',
98
+ model: row.modelID || row.modelId || 'unknown',
92
99
  project,
93
100
  timestamp,
94
101
  inputTokens: (tokens.input || 0) - cachedInput,
package/src/tools.js CHANGED
@@ -15,6 +15,7 @@ import { findClineDataDirs } from './cline-roots.js';
15
15
  import { findColaDataDirs, getColaSessionsDir } from './cola-roots.js';
16
16
  import { findCraftDataDirs } from './craft-roots.js';
17
17
  import { findHermesDataDirs, getHermesHome } from './hermes-roots.js';
18
+ import { findKimiCodeDataDirs } from './kimi-roots.js';
18
19
  import { findOmpDataDirs, findPiDataDirs } from './pi-roots.js';
19
20
  import { findQoderDataDirs, getQoderProjectsDir } from './qoder-roots.js';
20
21
  import { findWorkbuddyDataDirs } from './workbuddy-roots.js';
@@ -124,13 +125,8 @@ export function findCodexDataDirs(codexExtraHome, extraRoots = []) {
124
125
  }
125
126
 
126
127
  // Kimi Code moved its store from ~/.kimi to ~/.kimi-code; recognize either so
127
- // users on either version are detected. The parser prefers ~/.kimi-code.
128
- function findKimiCodeDataDirs() {
129
- return [
130
- join(homedir(), '.kimi-code', 'sessions'),
131
- join(homedir(), '.kimi', 'sessions'),
132
- ].filter(existsSync);
133
- }
128
+ // users on either version are detected. Kimi Work's embedded runtime home is
129
+ // recognized too — see kimi-roots.js, which the parser uses as well.
134
130
 
135
131
  /** DeepSeek Harness home: DSH_HOME env (same as the dsh CLI) or ~/.dsh. */
136
132
  export function getDshHome(env = process.env) {
@@ -176,6 +172,12 @@ export function getMimocodeDbPath(env = process.env) {
176
172
  return isAbsolute(env.MIMOCODE_DB) ? env.MIMOCODE_DB : join(dataDir, env.MIMOCODE_DB);
177
173
  }
178
174
 
175
+ export function getZcodeDbPath(env = process.env, home = homedir()) {
176
+ const override = env.VIBE_USAGE_ZCODE_DB?.trim();
177
+ if (override) return isAbsolute(override) ? override : resolve(override);
178
+ return join(home, '.zcode', 'cli', 'db', 'db.sqlite');
179
+ }
180
+
179
181
  export function findAntigravityDataDirs(extraRoots = []) {
180
182
  return [...new Set([
181
183
  ...antigravityConversationDirs(homedir()).map(dirname),
@@ -437,7 +439,7 @@ export const TOOLS = [
437
439
  {
438
440
  name: 'ZCode',
439
441
  id: 'zcode',
440
- dataDir: join(homedir(), '.zcode', 'cli', 'db', 'db.sqlite'),
442
+ dataDir: getZcodeDbPath(),
441
443
  },
442
444
  ];
443
445