@vibe-cafe/vibe-usage 0.9.1 → 0.9.3

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
@@ -66,6 +66,8 @@ npx @vibe-cafe/vibe-usage status # Show config & detected tools
66
66
  | Kiro | `~/Library/Application Support/Kiro/User/globalStorage/kiro.kiroagent/dev_data/devdata.sqlite` (SQLite, JSONL fallback; model name resolved from `.chat` timeline) |
67
67
  | Cline | `<host>/User/globalStorage/saoudrizwan.claude-dev/{state/taskHistory.json,tasks/<id>/ui_messages.json}` (walks all VSCode-fork hosts: Code, Cursor, Windsurf, VSCodium, Trae, ...) |
68
68
  | Roo Code | `<host>/User/globalStorage/rooveterinaryinc.roo-cline/{tasks/_index.json,tasks/<id>/{history_item,ui_messages}.json}` (walks all VSCode-fork hosts) |
69
+ | Antigravity | `~/.gemini/antigravity/conversations/*.pb` to discover cascades, then reads token usage + sessions from the running language server via Connect RPC (process discovered with `ps`/`lsof` on macOS/Linux, PowerShell CIM with a `wmic` fallback on Windows) |
70
+ | ZCode | `~/.zcode/cli/db/db.sqlite` (SQLite; reads the `message` table for per-message tokens, model, and project `cwd`/`root`, joined to `session.directory`) |
69
71
 
70
72
  ## How It Works
71
73
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibe-cafe/vibe-usage",
3
- "version": "0.9.1",
3
+ "version": "0.9.3",
4
4
  "description": "Track your AI coding tool token usage and sync to vibecafe.ai",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,5 +1,5 @@
1
1
  import { execSync } from 'node:child_process';
2
- import { readdirSync, existsSync } from 'node:fs';
2
+ import { readdirSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { homedir } from 'node:os';
5
5
  import { aggregateToBuckets, extractSessions } from './index.js';
@@ -57,27 +57,89 @@ function findLanguageServerUnix() {
57
57
  }
58
58
 
59
59
  function findLanguageServerWin() {
60
- const out = execSync(
61
- 'wmic process where "CommandLine like \'%antigravity%language_server%\'" get ProcessId,CommandLine /format:list',
62
- { encoding: 'utf-8', timeout: 5000, shell: 'cmd.exe' },
63
- );
64
- // wmic /format:list outputs lines like "CommandLine=..." and "ProcessId=..."
65
- let cmdLine = '';
60
+ // Prefer PowerShell/CIM: wmic is disabled by default on Windows 11 23H2+
61
+ // and removed entirely from 25H2 onward. Fall back to wmic for old/stripped
62
+ // environments without PowerShell. Each probe is independently time-boxed and
63
+ // failures are swallowed, so a missing/hung tool never blocks the next one or
64
+ // the parsers that run after antigravity.
65
+ const out = queryProcessesWinPowerShell() ?? queryProcessesWinWmic();
66
+ if (!out) return null;
67
+ return parseWinProcessList(out);
68
+ }
69
+
70
+ /**
71
+ * Query language_server processes via PowerShell + CIM.
72
+ * Emits "ProcessId=..." / "CommandLine=..." lines (wmic /format:list shape)
73
+ * so parseWinProcessList handles either source. Returns null on failure.
74
+ */
75
+ function queryProcessesWinPowerShell() {
76
+ // Filter is applied in PowerShell so the LIKE wildcards stay server-side.
77
+ // A "---" separator before each process's ProcessId/CommandLine lines keeps
78
+ // fields grouped even when multiple processes match.
79
+ const script =
80
+ "Get-CimInstance Win32_Process -Filter \"CommandLine LIKE '%antigravity%language_server%'\" | " +
81
+ 'ForEach-Object { "---"; "ProcessId=" + $_.ProcessId; "CommandLine=" + $_.CommandLine }';
82
+ for (const exe of ['powershell.exe', 'pwsh.exe']) {
83
+ try {
84
+ const out = execSync(
85
+ `${exe} -NoProfile -NonInteractive -Command "${script.replace(/"/g, '\\"')}"`,
86
+ { encoding: 'utf-8', timeout: 4000, windowsHide: true },
87
+ );
88
+ if (out && out.trim()) return out;
89
+ // Empty (no matching process) — no point trying another shell.
90
+ return null;
91
+ } catch {
92
+ // Try next shell (pwsh on systems without legacy powershell.exe).
93
+ }
94
+ }
95
+ return null;
96
+ }
97
+
98
+ /** Legacy fallback: wmic /format:list. Returns null on failure. */
99
+ function queryProcessesWinWmic() {
100
+ try {
101
+ return execSync(
102
+ 'wmic process where "CommandLine like \'%antigravity%language_server%\'" get ProcessId,CommandLine /format:list',
103
+ { encoding: 'utf-8', timeout: 4000, shell: 'cmd.exe' },
104
+ );
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Parse "ProcessId=..." / "CommandLine=..." records (from either PowerShell or
112
+ * wmic /format:list) and return the first language_server that carries a
113
+ * --csrf_token, or null. PowerShell emits an explicit "---" separator per
114
+ * process; wmic does not and may emit the two fields in either order, so a
115
+ * record also ends whenever a field we've already captured reappears.
116
+ */
117
+ function parseWinProcessList(out) {
66
118
  let pid = '';
119
+ let cmdLine = '';
120
+ const finish = () => {
121
+ if (pid && cmdLine && !/WMIC\.exe|powershell\.exe|pwsh\.exe/i.test(cmdLine)) {
122
+ const csrfMatch = cmdLine.match(/--csrf_token\s+([0-9a-f-]+)/);
123
+ if (csrfMatch) return { pid, csrfToken: csrfMatch[1] };
124
+ }
125
+ return null;
126
+ };
127
+ const reset = () => { pid = ''; cmdLine = ''; };
67
128
  for (const line of out.split('\n')) {
68
129
  const trimmed = line.trim();
69
- if (trimmed.startsWith('CommandLine=')) {
70
- const val = trimmed.slice('CommandLine='.length);
71
- if (/WMIC\.exe/i.test(val)) continue; // skip wmic's own process
72
- cmdLine = val;
130
+ const isPid = trimmed.startsWith('ProcessId=');
131
+ const isCmd = trimmed.startsWith('CommandLine=');
132
+ // Record boundary: explicit "---", or a field that would overwrite one we
133
+ // already hold (next process began without a separator, e.g. wmic output).
134
+ if (trimmed === '---' || (isPid && pid) || (isCmd && cmdLine)) {
135
+ const found = finish();
136
+ if (found) return found;
137
+ reset();
73
138
  }
74
- if (trimmed.startsWith('ProcessId=')) pid = trimmed.slice('ProcessId='.length);
139
+ if (isPid) pid = trimmed.slice('ProcessId='.length);
140
+ else if (isCmd) cmdLine = trimmed.slice('CommandLine='.length);
75
141
  }
76
- if (!pid || !cmdLine) return null;
77
- const csrfMatch = cmdLine.match(/--csrf_token\s+([0-9a-f-]+)/);
78
- const csrfToken = csrfMatch ? csrfMatch[1] : '';
79
- if (!csrfToken) return null;
80
- return { pid, csrfToken };
142
+ return finish();
81
143
  }
82
144
 
83
145
  function findListeningPorts(pid) {
@@ -16,6 +16,7 @@ import { parse as parseAntigravity } from './antigravity.js';
16
16
  import { parse as parseHermes } from './hermes.js';
17
17
  import { parse as parseKiro } from './kiro.js';
18
18
  import { parse as parsePiCodingAgent } from './pi-coding-agent.js';
19
+ import { parse as parseZcode } from './zcode.js';
19
20
 
20
21
  export const parsers = {
21
22
  'claude-code': parseClaudeCode,
@@ -35,6 +36,7 @@ export const parsers = {
35
36
  'hermes': parseHermes,
36
37
  'kiro': parseKiro,
37
38
  'pi-coding-agent': parsePiCodingAgent,
39
+ 'zcode': parseZcode,
38
40
  };
39
41
 
40
42
 
@@ -0,0 +1,104 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join, basename } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { aggregateToBuckets, extractSessions } from './index.js';
5
+ import { queryDbJson } from './sqlite.js';
6
+
7
+ // ZCode (z.ai / Zhipu's coding agent) stores everything in a SQLite database
8
+ // at ~/.zcode/cli/db/db.sqlite. The `message` table is the canonical source:
9
+ // each row is one user or assistant message, with an assistant message carrying
10
+ // per-request token usage and the working directory. We read it directly rather
11
+ // than the parallel `model_usage` ledger because `message` gives us BOTH session
12
+ // timing (user + assistant rows) and token usage in one pass, with the project
13
+ // path attached to each message.
14
+ const DB_PATH = join(homedir(), '.zcode', 'cli', 'db', 'db.sqlite');
15
+
16
+ /**
17
+ * Project name from a ZCode message's path. ZCode records both `cwd` and `root`;
18
+ * prefer `root` (the workspace root) and fall back to `cwd`, then to the
19
+ * session's `directory` column (joined in via the query) — taking the last path
20
+ * component, matching how every other parser names projects.
21
+ */
22
+ function projectName(root, cwd, sessionDir) {
23
+ const p = root || cwd || sessionDir;
24
+ if (!p) return 'unknown';
25
+ return basename(String(p).replace(/[/\\]+$/, '')) || 'unknown';
26
+ }
27
+
28
+ export async function parse() {
29
+ if (!existsSync(DB_PATH)) return { buckets: [], sessions: [] };
30
+
31
+ // Join each message to its session so we can fall back to the session's
32
+ // directory when an individual message has no path (older rows, lite agents).
33
+ const query = `SELECT
34
+ m.session_id AS sessionId,
35
+ m.time_created AS created,
36
+ json_extract(m.data, '$.role') AS role,
37
+ json_extract(m.data, '$.modelID') AS modelID,
38
+ json_extract(m.data, '$.tokens') AS tokens,
39
+ json_extract(m.data, '$.path.root') AS pathRoot,
40
+ json_extract(m.data, '$.path.cwd') AS pathCwd,
41
+ s.directory AS sessionDir
42
+ FROM message m
43
+ LEFT JOIN session s ON s.id = m.session_id`;
44
+
45
+ let rows;
46
+ try {
47
+ rows = queryDbJson(DB_PATH, query);
48
+ } catch (err) {
49
+ if (err.status === 127 || (err.message && err.message.includes('ENOENT'))) {
50
+ throw new Error('sqlite3 CLI not found. Install sqlite3 (or use Node >= 22.5) to sync ZCode data.');
51
+ }
52
+ throw err;
53
+ }
54
+ if (!rows.length) return { buckets: [], sessions: [] };
55
+
56
+ const entries = [];
57
+ const sessionEvents = [];
58
+
59
+ for (const row of rows) {
60
+ const timestamp = new Date(row.created);
61
+ if (isNaN(timestamp.getTime())) continue;
62
+
63
+ const project = projectName(row.pathRoot, row.pathCwd, row.sessionDir);
64
+ const sessionId = row.sessionId || 'unknown';
65
+
66
+ sessionEvents.push({
67
+ sessionId,
68
+ source: 'zcode',
69
+ project,
70
+ timestamp,
71
+ role: row.role === 'user' ? 'user' : 'assistant',
72
+ });
73
+
74
+ if (row.role !== 'assistant') continue;
75
+
76
+ let tokens;
77
+ try {
78
+ tokens = typeof row.tokens === 'string' ? JSON.parse(row.tokens) : row.tokens;
79
+ } catch {
80
+ continue;
81
+ }
82
+ if (!tokens || (!tokens.input && !tokens.output)) continue;
83
+
84
+ // ZCode follows Anthropic-style usage where `input` INCLUDES the cache-read
85
+ // tokens and `output` INCLUDES reasoning (verified: input + output == total).
86
+ // Normalize to this codebase's non-overlapping fields so cached/reasoning
87
+ // tokens aren't double-counted inside input/output.
88
+ const cachedInput = tokens.cache?.read || 0;
89
+ const reasoning = tokens.reasoning || 0;
90
+
91
+ entries.push({
92
+ source: 'zcode',
93
+ model: row.modelID || 'unknown',
94
+ project,
95
+ timestamp,
96
+ inputTokens: (tokens.input || 0) - cachedInput,
97
+ outputTokens: (tokens.output || 0) - reasoning,
98
+ cachedInputTokens: cachedInput,
99
+ reasoningOutputTokens: reasoning,
100
+ });
101
+ }
102
+
103
+ return { buckets: aggregateToBuckets(entries), sessions: extractSessions(sessionEvents) };
104
+ }
package/src/tools.js CHANGED
@@ -195,6 +195,11 @@ export const TOOLS = [
195
195
  dataDir: join(homedir(), 'Library', 'Application Support', 'Code', 'User', 'globalStorage', 'rooveterinaryinc.roo-cline'),
196
196
  detectDataDirs: findRooCodeDataDirs,
197
197
  },
198
+ {
199
+ name: 'ZCode',
200
+ id: 'zcode',
201
+ dataDir: join(homedir(), '.zcode', 'cli', 'db', 'db.sqlite'),
202
+ },
198
203
  ];
199
204
 
200
205
  export function detectInstalledTools() {