tokenusage-cli 0.1.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.
- package/CHANGELOG.md +19 -0
- package/LICENSE +22 -0
- package/README.md +94 -0
- package/THIRD_PARTY_NOTICES.md +140 -0
- package/bin/tokenusage.js +69 -0
- package/package.json +59 -0
- package/src/cli.js +134 -0
- package/src/commands/device-login.js +205 -0
- package/src/commands/diagnostics.js +38 -0
- package/src/commands/doctor.js +110 -0
- package/src/commands/init.js +2436 -0
- package/src/commands/sessions.js +29 -0
- package/src/commands/status.js +1747 -0
- package/src/commands/sync.js +7934 -0
- package/src/commands/uninstall.js +312 -0
- package/src/lib/account-usage-dedup.js +267 -0
- package/src/lib/antigravity-paths.js +48 -0
- package/src/lib/ark-agent-plan-limits.js +438 -0
- package/src/lib/ark-coding-plan-limits.js +537 -0
- package/src/lib/async-queue-reader.js +138 -0
- package/src/lib/atomic-json.js +27 -0
- package/src/lib/bearer-token.js +11 -0
- package/src/lib/categorizer-utils.js +232 -0
- package/src/lib/claude-categorizer.js +1343 -0
- package/src/lib/claude-config.js +279 -0
- package/src/lib/claude-user-identity.js +56 -0
- package/src/lib/cli-ui.js +179 -0
- package/src/lib/cloud-account.js +541 -0
- package/src/lib/cloud-device-token.js +141 -0
- package/src/lib/cloud-sync-prefs.js +14 -0
- package/src/lib/cloud-usage-reset.js +115 -0
- package/src/lib/codex-config.js +595 -0
- package/src/lib/codex-context-breakdown.js +806 -0
- package/src/lib/codex-model-attribution.js +128 -0
- package/src/lib/codex-rollout-parser.js +1471 -0
- package/src/lib/codex-service-tier.js +49 -0
- package/src/lib/codex-token-refresh.js +140 -0
- package/src/lib/codex-token-usage.js +195 -0
- package/src/lib/codex-usage-record.js +195 -0
- package/src/lib/command-runner.js +313 -0
- package/src/lib/commandcode-limits.js +317 -0
- package/src/lib/context-health.js +124 -0
- package/src/lib/cursor-config.js +605 -0
- package/src/lib/cursor-store.js +1918 -0
- package/src/lib/debug-flags.js +7 -0
- package/src/lib/devin-limits.js +249 -0
- package/src/lib/devin-usage.js +212 -0
- package/src/lib/diagnostics.js +383 -0
- package/src/lib/doctor.js +385 -0
- package/src/lib/dumate.js +95 -0
- package/src/lib/fs.js +455 -0
- package/src/lib/function-url.js +14 -0
- package/src/lib/gemini-config.js +291 -0
- package/src/lib/git-outcomes.js +243 -0
- package/src/lib/grok-context-breakdown.js +890 -0
- package/src/lib/grok-hook.js +360 -0
- package/src/lib/grok-limits.js +865 -0
- package/src/lib/grok-usage.js +98 -0
- package/src/lib/heatmap-compact.js +114 -0
- package/src/lib/ingest-sanitize.js +41 -0
- package/src/lib/init-flow.js +42 -0
- package/src/lib/install-resolver.js +170 -0
- package/src/lib/jsonl-lines.js +134 -0
- package/src/lib/kimi-model-repair.js +173 -0
- package/src/lib/kimi-profile.js +61 -0
- package/src/lib/kimi-session.js +216 -0
- package/src/lib/local-api.js +3588 -0
- package/src/lib/machine-id.js +238 -0
- package/src/lib/multi-install-parser.js +113 -0
- package/src/lib/notify-command.js +38 -0
- package/src/lib/omp-hook.js +589 -0
- package/src/lib/openclaw-cli.js +104 -0
- package/src/lib/openclaw-hook.js +375 -0
- package/src/lib/openclaw-session-plugin.js +560 -0
- package/src/lib/opencode-config.js +121 -0
- package/src/lib/opencode-go-limits.js +807 -0
- package/src/lib/outcomes-engine.js +253 -0
- package/src/lib/passive-mode.js +219 -0
- package/src/lib/pet-packages.js +722 -0
- package/src/lib/pricing/curated-overrides.json +822 -0
- package/src/lib/pricing/index.js +379 -0
- package/src/lib/pricing/litellm-fetcher.js +172 -0
- package/src/lib/pricing/matcher.js +456 -0
- package/src/lib/pricing/seed-snapshot.json +1 -0
- package/src/lib/progress.js +76 -0
- package/src/lib/project-usage-purge.js +117 -0
- package/src/lib/prompt.js +24 -0
- package/src/lib/provider-status.js +104 -0
- package/src/lib/proxy-env.js +489 -0
- package/src/lib/proxy-settings.js +163 -0
- package/src/lib/qoder-cn-cli-limits.js +119 -0
- package/src/lib/qoder-limits.js +880 -0
- package/src/lib/quiet-warnings.js +26 -0
- package/src/lib/rollout.js +25966 -0
- package/src/lib/runtime-config.js +259 -0
- package/src/lib/scan-roots.js +277 -0
- package/src/lib/sentry.js +231 -0
- package/src/lib/session-analytics.js +2972 -0
- package/src/lib/session-performance.js +237 -0
- package/src/lib/session-upload.js +379 -0
- package/src/lib/skill-usage.js +267 -0
- package/src/lib/skills-manager.js +1591 -0
- package/src/lib/source-metadata.js +48 -0
- package/src/lib/sqlite-reader.js +215 -0
- package/src/lib/star-cta.js +73 -0
- package/src/lib/subscription-manager.js +293 -0
- package/src/lib/subscriptions.js +508 -0
- package/src/lib/telemetry.js +193 -0
- package/src/lib/tracker-paths.js +16 -0
- package/src/lib/trae-cn-config.js +548 -0
- package/src/lib/trae-db.js +127 -0
- package/src/lib/trae-snapshot.js +230 -0
- package/src/lib/trae-sqlite.js +143 -0
- package/src/lib/trae-usage.js +121 -0
- package/src/lib/upload-queue.js +134 -0
- package/src/lib/upload-throttle.js +171 -0
- package/src/lib/usage-limits.js +4552 -0
- package/src/lib/wrapped-aggregator.js +236 -0
- package/src/lib/wsl-probe.js +281 -0
- package/src/lib/zcode-limits.js +1172 -0
- package/src/lib/zcode-reset-credits.js +66 -0
- package/test/cli-smoke.test.js +53 -0
- package/test/ingest-sanitize.test.js +162 -0
- package/test/quiet-warnings.test.js +53 -0
- package/test/session-upload.test.js +427 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
// Quality-per-dollar / Effective-Tokens engine (opt-in, sidecar)
|
|
5
|
+
//
|
|
6
|
+
// Token Usage answers "what did the tokens COST?". This optional layer adds
|
|
7
|
+
// "what did they BUY?" by joining an opt-in, vendor-neutral `outcomes.jsonl`
|
|
8
|
+
// sidecar to the existing token/$ rows by model + time.
|
|
9
|
+
//
|
|
10
|
+
// Design invariants (see GitHub #229):
|
|
11
|
+
// 1. SIDECAR, never the hot path. This module only ever READS its own file
|
|
12
|
+
// and the already-parsed queue rows. It never touches queue.jsonl, its
|
|
13
|
+
// schema, or the sync path. A bug here cannot corrupt token/$ data.
|
|
14
|
+
// 2. DEGRADES TO COST-ONLY. No outcomes file -> readOutcomesData returns []
|
|
15
|
+
// and every join yields empty, so callers render exactly as today.
|
|
16
|
+
// 3. METADATA-ONLY. sanitizeOutcome whitelists a tiny set of scalar fields
|
|
17
|
+
// and drops everything else, so a mis-populated sidecar can NEVER surface
|
|
18
|
+
// PR bodies, diffs, or message text into the dashboard.
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
|
|
21
|
+
const fs = require("node:fs");
|
|
22
|
+
const os = require("node:os");
|
|
23
|
+
const path = require("node:path");
|
|
24
|
+
const { computeRowCost } = require("./pricing");
|
|
25
|
+
|
|
26
|
+
function resolveOutcomesPath() {
|
|
27
|
+
return path.join(os.homedir(), ".tokenusage", "tracker", "outcomes.jsonl");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function resolveAutoOutcomesPath() {
|
|
31
|
+
return path.join(os.homedir(), ".tokenusage", "tracker", "auto-outcomes.jsonl");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// The ONLY fields ever lifted off an outcome record. Anything not on this list
|
|
35
|
+
// — bodies, diffs, messages, arbitrary blobs — is dropped at read time. This is
|
|
36
|
+
// the enforcement point for the metadata-only privacy invariant.
|
|
37
|
+
function sanitizeOutcome(raw) {
|
|
38
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
|
39
|
+
const timestamp = typeof raw.timestamp === "string" ? raw.timestamp.trim() : "";
|
|
40
|
+
if (!timestamp) return null; // an outcome with no time can't be joined to $ rows
|
|
41
|
+
|
|
42
|
+
// `accepted` is the gate signal: a merged PR / passed task. Strictly boolean
|
|
43
|
+
// — anything other than literal true counts as not-accepted (rework).
|
|
44
|
+
const accepted = raw.accepted === true;
|
|
45
|
+
|
|
46
|
+
const model =
|
|
47
|
+
typeof raw.model === "string" && raw.model.trim() ? raw.model.trim() : "unknown";
|
|
48
|
+
// `tool` mirrors the queue row's `source` (claude, codex, cursor, …). Accept
|
|
49
|
+
// either key so writers can use whichever they have on hand.
|
|
50
|
+
const toolRaw =
|
|
51
|
+
(typeof raw.tool === "string" && raw.tool.trim() && raw.tool) ||
|
|
52
|
+
(typeof raw.source === "string" && raw.source.trim() && raw.source) ||
|
|
53
|
+
"";
|
|
54
|
+
const tool = toolRaw ? String(toolRaw).trim() : "unknown";
|
|
55
|
+
|
|
56
|
+
const out = { timestamp, model, tool, accepted };
|
|
57
|
+
// task_type is an optional, low-cardinality label (e.g. "feature", "bugfix").
|
|
58
|
+
if (typeof raw.task_type === "string" && raw.task_type.trim()) {
|
|
59
|
+
out.task_type = raw.task_type.trim();
|
|
60
|
+
}
|
|
61
|
+
for (const key of ["status", "session_hash", "commit_hash", "confidence", "methodology"]) {
|
|
62
|
+
if (typeof raw[key] === "string" && raw[key].trim()) out[key] = raw[key].trim();
|
|
63
|
+
}
|
|
64
|
+
if (Number.isFinite(Number(raw.parent_count))) out.parent_count = Number(raw.parent_count);
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function readOutcomesData(outcomesPath) {
|
|
69
|
+
let raw;
|
|
70
|
+
try {
|
|
71
|
+
raw = fs.readFileSync(outcomesPath, "utf8");
|
|
72
|
+
} catch (e) {
|
|
73
|
+
// ENOENT is the normal "user hasn't opted in" case — silent. Anything else
|
|
74
|
+
// is surfaced once so a genuinely unreadable file isn't hidden forever.
|
|
75
|
+
if (e && e.code !== "ENOENT") {
|
|
76
|
+
console.error("[outcomes] read failed:", (e && e.message) || e);
|
|
77
|
+
}
|
|
78
|
+
return [];
|
|
79
|
+
}
|
|
80
|
+
const out = [];
|
|
81
|
+
let malformed = 0;
|
|
82
|
+
for (const line of raw.split("\n")) {
|
|
83
|
+
const trimmed = line.trim();
|
|
84
|
+
if (!trimmed) continue;
|
|
85
|
+
let parsed;
|
|
86
|
+
try {
|
|
87
|
+
parsed = JSON.parse(trimmed);
|
|
88
|
+
} catch {
|
|
89
|
+
malformed += 1;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const rec = sanitizeOutcome(parsed);
|
|
93
|
+
if (rec) out.push(rec);
|
|
94
|
+
else malformed += 1;
|
|
95
|
+
}
|
|
96
|
+
if (malformed > 0) {
|
|
97
|
+
console.error(`[outcomes] skipped ${malformed} malformed/invalid line(s) in ${outcomesPath}`);
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function readAllOutcomesData(paths = [resolveOutcomesPath(), resolveAutoOutcomesPath()]) {
|
|
103
|
+
const dedup = new Map();
|
|
104
|
+
for (const outcomePath of paths) {
|
|
105
|
+
for (const row of readOutcomesData(outcomePath)) {
|
|
106
|
+
const key = row.commit_hash
|
|
107
|
+
? `commit:${row.commit_hash}`
|
|
108
|
+
: `${row.timestamp}|${row.model}|${row.tool}|${row.task_type || ""}`;
|
|
109
|
+
dedup.set(key, row);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return [...dedup.values()];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function dayOf(value) {
|
|
116
|
+
return typeof value === "string" ? value.slice(0, 10) : "";
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function inWindow(dayStr, from, to) {
|
|
120
|
+
if (from && dayStr && dayStr < from) return false;
|
|
121
|
+
if (to && dayStr && dayStr > to) return false;
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function bumpCost(map, key, cost, tokens) {
|
|
126
|
+
let agg = map.get(key);
|
|
127
|
+
if (!agg) {
|
|
128
|
+
agg = { cost_usd: 0, total_tokens: 0 };
|
|
129
|
+
map.set(key, agg);
|
|
130
|
+
}
|
|
131
|
+
agg.cost_usd += cost;
|
|
132
|
+
agg.total_tokens += tokens;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function bumpOutcome(map, key, accepted) {
|
|
136
|
+
let agg = map.get(key);
|
|
137
|
+
if (!agg) {
|
|
138
|
+
agg = { accepted: 0, outcomes: 0 };
|
|
139
|
+
map.set(key, agg);
|
|
140
|
+
}
|
|
141
|
+
agg.outcomes += 1;
|
|
142
|
+
if (accepted) agg.accepted += 1;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function combineRow(key, cost, out) {
|
|
146
|
+
const cost_usd = cost ? cost.cost_usd : 0;
|
|
147
|
+
const total_tokens = cost ? cost.total_tokens : 0;
|
|
148
|
+
const accepted = out ? out.accepted : 0;
|
|
149
|
+
const outcomes = out ? out.outcomes : 0;
|
|
150
|
+
const acceptance_rate = outcomes > 0 ? accepted / outcomes : null;
|
|
151
|
+
// quality per dollar = accepted, gate-passing outcomes ÷ dollars spent.
|
|
152
|
+
// Null (not zero) when we can't form the ratio — no spend or no outcomes —
|
|
153
|
+
// so the UI can distinguish "0 quality" from "not enough data".
|
|
154
|
+
const quality_per_dollar = cost_usd > 0 && outcomes > 0 ? accepted / cost_usd : null;
|
|
155
|
+
// Effective Tokens: the share of tokens that produced accepted work.
|
|
156
|
+
const effective_tokens = acceptance_rate === null ? null : total_tokens * acceptance_rate;
|
|
157
|
+
const effective_cost_usd = acceptance_rate === null ? null : cost_usd * acceptance_rate;
|
|
158
|
+
return {
|
|
159
|
+
key,
|
|
160
|
+
cost_usd,
|
|
161
|
+
total_tokens,
|
|
162
|
+
accepted,
|
|
163
|
+
outcomes,
|
|
164
|
+
acceptance_rate,
|
|
165
|
+
quality_per_dollar,
|
|
166
|
+
effective_tokens,
|
|
167
|
+
effective_cost_usd,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function combine(costMap, outMap) {
|
|
172
|
+
const keys = new Set([...costMap.keys(), ...outMap.keys()]);
|
|
173
|
+
const rows = [];
|
|
174
|
+
for (const key of keys) {
|
|
175
|
+
rows.push(combineRow(key, costMap.get(key), outMap.get(key)));
|
|
176
|
+
}
|
|
177
|
+
// Highest quality-per-dollar first; rows without a ratio sink to the bottom.
|
|
178
|
+
rows.sort((a, b) => {
|
|
179
|
+
const av = a.quality_per_dollar;
|
|
180
|
+
const bv = b.quality_per_dollar;
|
|
181
|
+
if (av === null && bv === null) return b.outcomes - a.outcomes;
|
|
182
|
+
if (av === null) return 1;
|
|
183
|
+
if (bv === null) return -1;
|
|
184
|
+
return bv - av;
|
|
185
|
+
});
|
|
186
|
+
return rows;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Join outcomes to token/$ rows by model + tool, within an optional [from,to]
|
|
191
|
+
* day window. Returns per-model and per-tool quality-per-dollar / ET, plus
|
|
192
|
+
* totals. Pure: no I/O, no mutation of inputs.
|
|
193
|
+
*
|
|
194
|
+
* @param {Array} queueRows already-parsed queue rows ({ source, model, hour_start, …token fields })
|
|
195
|
+
* @param {Array} outcomes sanitized outcome records (from readOutcomesData)
|
|
196
|
+
* @param {{from?:string,to?:string}} [window]
|
|
197
|
+
*/
|
|
198
|
+
function computeQualityPerDollar(queueRows, outcomes, { from = "", to = "" } = {}) {
|
|
199
|
+
const modelCost = new Map();
|
|
200
|
+
const toolCost = new Map();
|
|
201
|
+
for (const row of queueRows || []) {
|
|
202
|
+
if (!row || typeof row !== "object") continue; // tolerate a stray null/garbage line
|
|
203
|
+
const day = dayOf(row.hour_start);
|
|
204
|
+
if ((from || to) && !inWindow(day, from, to)) continue;
|
|
205
|
+
const model = (row && row.model) || "unknown";
|
|
206
|
+
const tool = (row && row.source) || "unknown";
|
|
207
|
+
const cost = computeRowCost(row) || 0;
|
|
208
|
+
const tokens = Number((row && row.total_tokens) || 0);
|
|
209
|
+
bumpCost(modelCost, model, cost, tokens);
|
|
210
|
+
bumpCost(toolCost, tool, cost, tokens);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const modelOut = new Map();
|
|
214
|
+
const toolOut = new Map();
|
|
215
|
+
for (const o of outcomes || []) {
|
|
216
|
+
const day = dayOf(o && o.timestamp);
|
|
217
|
+
if ((from || to) && !inWindow(day, from, to)) continue;
|
|
218
|
+
bumpOutcome(modelOut, (o && o.model) || "unknown", !!(o && o.accepted));
|
|
219
|
+
bumpOutcome(toolOut, (o && o.tool) || "unknown", !!(o && o.accepted));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const by_model = combine(modelCost, modelOut);
|
|
223
|
+
const by_tool = combine(toolCost, toolOut);
|
|
224
|
+
|
|
225
|
+
let totalCost = 0;
|
|
226
|
+
let totalTokens = 0;
|
|
227
|
+
for (const v of modelCost.values()) {
|
|
228
|
+
totalCost += v.cost_usd;
|
|
229
|
+
totalTokens += v.total_tokens;
|
|
230
|
+
}
|
|
231
|
+
let totalAccepted = 0;
|
|
232
|
+
let totalOutcomes = 0;
|
|
233
|
+
for (const v of modelOut.values()) {
|
|
234
|
+
totalAccepted += v.accepted;
|
|
235
|
+
totalOutcomes += v.outcomes;
|
|
236
|
+
}
|
|
237
|
+
const totals = combineRow(
|
|
238
|
+
"__all__",
|
|
239
|
+
{ cost_usd: totalCost, total_tokens: totalTokens },
|
|
240
|
+
{ accepted: totalAccepted, outcomes: totalOutcomes },
|
|
241
|
+
);
|
|
242
|
+
|
|
243
|
+
return { available: outcomes && outcomes.length > 0, by_model, by_tool, totals };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
module.exports = {
|
|
247
|
+
resolveOutcomesPath,
|
|
248
|
+
resolveAutoOutcomesPath,
|
|
249
|
+
sanitizeOutcome,
|
|
250
|
+
readOutcomesData,
|
|
251
|
+
readAllOutcomesData,
|
|
252
|
+
computeQualityPerDollar,
|
|
253
|
+
};
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Passive-mode detection.
|
|
3
|
+
*
|
|
4
|
+
* Token Tracker normally collects token usage by installing SessionEnd hooks
|
|
5
|
+
* into supported CLIs (Claude Code, Codex CLI, Gemini CLI, …). The hook
|
|
6
|
+
* fires `notify.cjs` after each turn → sync runs immediately → data is
|
|
7
|
+
* fresh within seconds.
|
|
8
|
+
*
|
|
9
|
+
* On environments where hook installation fails — WSL with read-only mount,
|
|
10
|
+
* UNC paths on Windows, locked `settings.json`, sandboxed processes —
|
|
11
|
+
* SessionEnd hooks never fire, but the underlying CLIs *still* write
|
|
12
|
+
* session logs (`~/.claude/projects/`, `~/.gemini/sessions/`, etc.). Our
|
|
13
|
+
* parsers can read those logs directly without the hook; the only loss is
|
|
14
|
+
* "data is fresh within seconds" → it's now "data is fresh after the next
|
|
15
|
+
* scheduled `tracker sync`".
|
|
16
|
+
*
|
|
17
|
+
* This module surfaces that fact: for each hook-driven provider, decide
|
|
18
|
+
* whether the local install is in **passive mode** (no hook + log dir
|
|
19
|
+
* present). `tracker status` reports it, and the dashboard can show a
|
|
20
|
+
* single banner asking the user whether to acknowledge & continue in
|
|
21
|
+
* passive mode or attempt re-install (`tracker init`).
|
|
22
|
+
*
|
|
23
|
+
* Detection is purely best-effort — we never *fail* sync because hooks are
|
|
24
|
+
* missing; we just label the source so users / AI agents know latency is
|
|
25
|
+
* minutes, not seconds.
|
|
26
|
+
*/
|
|
27
|
+
"use strict";
|
|
28
|
+
|
|
29
|
+
const fs = require("node:fs");
|
|
30
|
+
const path = require("node:path");
|
|
31
|
+
const { expandHome } = require("./scan-roots");
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @typedef {Object} PassiveProvider
|
|
35
|
+
* @property {string} name - canonical provider name
|
|
36
|
+
* @property {boolean} hook_expected - whether this provider supports hooks
|
|
37
|
+
* @property {boolean} hook_installed - true when the hook is set
|
|
38
|
+
* @property {boolean} logs_present - true when the provider's log dir
|
|
39
|
+
* exists and contains at least one
|
|
40
|
+
* session file we can parse
|
|
41
|
+
* @property {boolean} passive - true iff hook_expected &&
|
|
42
|
+
* !hook_installed && logs_present
|
|
43
|
+
* @property {string|null} hook_failure_reason - if hook_expected and not
|
|
44
|
+
* installed, why we think it failed
|
|
45
|
+
* (e.g. "settings.json not writable",
|
|
46
|
+
* "config dir not found")
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
function dirHasFile(dir, predicate) {
|
|
50
|
+
if (!dir || !fs.existsSync(dir)) return false;
|
|
51
|
+
let entries;
|
|
52
|
+
try {
|
|
53
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
54
|
+
} catch (_e) {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
for (const entry of entries) {
|
|
58
|
+
const full = path.join(dir, entry.name);
|
|
59
|
+
// Let the predicate accept either a file OR a directory name (so
|
|
60
|
+
// "sessions" or "tmp" as a bare subdirectory still counts).
|
|
61
|
+
if (!predicate || predicate(full, entry.name, entry.isDirectory())) return true;
|
|
62
|
+
if (entry.isDirectory()) {
|
|
63
|
+
// Shallow recurse — at most 1 level (covers projects/<name>/*.jsonl)
|
|
64
|
+
if (dirHasFile(full, predicate)) return true;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function classifyWritableFailure(filePath) {
|
|
71
|
+
if (!filePath) return "no path";
|
|
72
|
+
try {
|
|
73
|
+
fs.accessSync(filePath, fs.constants.W_OK);
|
|
74
|
+
return "writable (hook may have been removed externally)";
|
|
75
|
+
} catch (e) {
|
|
76
|
+
if (e && e.code === "ENOENT") return "settings file missing";
|
|
77
|
+
if (e && e.code === "EACCES") return "permission denied";
|
|
78
|
+
if (e && e.code === "EROFS") return "read-only filesystem";
|
|
79
|
+
return e?.code || "unknown";
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Detect passive mode for each hook-driven provider.
|
|
85
|
+
*
|
|
86
|
+
* @param {Object} opts
|
|
87
|
+
* @param {string} opts.home - user home directory
|
|
88
|
+
* @param {Object} opts.hookStatus - per-provider hook-installed booleans
|
|
89
|
+
* (already collected by status.js); shape: { claude, gemini, codex,
|
|
90
|
+
* every_code, opencode, openclaw, codebuddy, workbuddy, grok }
|
|
91
|
+
* @returns {PassiveProvider[]}
|
|
92
|
+
*/
|
|
93
|
+
function detectPassiveProviders({ home, hookStatus, env = process.env }) {
|
|
94
|
+
const out = [];
|
|
95
|
+
|
|
96
|
+
// Claude Code — logs at ~/.claude/projects/<name>/*.jsonl
|
|
97
|
+
out.push(buildEntry({
|
|
98
|
+
name: "claude",
|
|
99
|
+
hookExpected: true,
|
|
100
|
+
hookInstalled: Boolean(hookStatus?.claude),
|
|
101
|
+
logsDir: path.join(home, ".claude", "projects"),
|
|
102
|
+
logsPredicate: (full) => full.endsWith(".jsonl"),
|
|
103
|
+
settingsPath: path.join(home, ".claude", "settings.json"),
|
|
104
|
+
}));
|
|
105
|
+
|
|
106
|
+
// Gemini CLI — logs at ~/.gemini/tmp/<session-id>/logs.json
|
|
107
|
+
// (path varies by version; presence of ~/.gemini/sessions or
|
|
108
|
+
// ~/.gemini/tmp is enough to call it "active")
|
|
109
|
+
out.push(buildEntry({
|
|
110
|
+
name: "gemini",
|
|
111
|
+
hookExpected: true,
|
|
112
|
+
hookInstalled: Boolean(hookStatus?.gemini),
|
|
113
|
+
logsDir: path.join(home, ".gemini"),
|
|
114
|
+
logsPredicate: (_full, name, isDir) =>
|
|
115
|
+
(isDir && (name === "tmp" || name === "sessions")) || name === "logs.json",
|
|
116
|
+
settingsPath: path.join(home, ".gemini", "settings.json"),
|
|
117
|
+
}));
|
|
118
|
+
|
|
119
|
+
// Codex CLI — logs at ~/.codex/sessions/
|
|
120
|
+
// Match either a "sessions" subdir (even if empty — the CLI created it)
|
|
121
|
+
// or any *.jsonl session file.
|
|
122
|
+
out.push(buildEntry({
|
|
123
|
+
name: "codex",
|
|
124
|
+
hookExpected: true,
|
|
125
|
+
hookInstalled: Boolean(hookStatus?.codex_notify ?? hookStatus?.codex),
|
|
126
|
+
logsDir: path.join(home, ".codex"),
|
|
127
|
+
logsPredicate: (_full, name, isDir) =>
|
|
128
|
+
(isDir && name === "sessions") || (!isDir && name.endsWith(".jsonl")),
|
|
129
|
+
settingsPath: path.join(home, ".codex", "config.toml"),
|
|
130
|
+
}));
|
|
131
|
+
|
|
132
|
+
const acodeHome = env.TOKENUSAGE_ACODE_HOME || path.join(home, ".acode");
|
|
133
|
+
out.push(buildEntry({
|
|
134
|
+
name: "acode",
|
|
135
|
+
hookExpected: true,
|
|
136
|
+
hookInstalled: Boolean(hookStatus?.acode_notify ?? hookStatus?.acode),
|
|
137
|
+
logsDir: acodeHome,
|
|
138
|
+
logsPredicate: (_full, name, isDir) =>
|
|
139
|
+
(isDir && (name === "sessions" || name === "archived_sessions")) ||
|
|
140
|
+
(!isDir && name.endsWith(".jsonl")),
|
|
141
|
+
settingsPath: path.join(acodeHome, "config.toml"),
|
|
142
|
+
}));
|
|
143
|
+
|
|
144
|
+
// Every Code — same shape as Codex, different home
|
|
145
|
+
out.push(buildEntry({
|
|
146
|
+
name: "every_code",
|
|
147
|
+
hookExpected: true,
|
|
148
|
+
hookInstalled: Boolean(hookStatus?.every_code_notify ?? hookStatus?.every_code),
|
|
149
|
+
logsDir: path.join(home, ".code"),
|
|
150
|
+
logsPredicate: (_full, name, isDir) =>
|
|
151
|
+
(isDir && name === "sessions") || (!isDir && name.endsWith(".jsonl")),
|
|
152
|
+
settingsPath: path.join(home, ".code", "config.toml"),
|
|
153
|
+
}));
|
|
154
|
+
|
|
155
|
+
// CodeBuddy — Claude-fork; hook in ~/.codebuddy/settings.json
|
|
156
|
+
out.push(buildEntry({
|
|
157
|
+
name: "codebuddy",
|
|
158
|
+
hookExpected: true,
|
|
159
|
+
hookInstalled: Boolean(hookStatus?.codebuddy),
|
|
160
|
+
logsDir: path.join(home, ".codebuddy"),
|
|
161
|
+
logsPredicate: (_full, name) => name === "projects" || name.endsWith(".jsonl"),
|
|
162
|
+
settingsPath: path.join(home, ".codebuddy", "settings.json"),
|
|
163
|
+
}));
|
|
164
|
+
|
|
165
|
+
// WorkBuddy — sibling Claude-fork; hook in ~/.workbuddy/settings.json
|
|
166
|
+
out.push(buildEntry({
|
|
167
|
+
name: "workbuddy",
|
|
168
|
+
hookExpected: true,
|
|
169
|
+
hookInstalled: Boolean(hookStatus?.workbuddy),
|
|
170
|
+
logsDir: path.join(home, ".workbuddy"),
|
|
171
|
+
logsPredicate: (_full, name) => name === "projects" || name.endsWith(".jsonl"),
|
|
172
|
+
settingsPath: path.join(home, ".workbuddy", "settings.json"),
|
|
173
|
+
}));
|
|
174
|
+
|
|
175
|
+
// WorkBuddy AI — international build; data + hooks in ~/.workbuddy-ai
|
|
176
|
+
const workbuddyAiHome = expandHome(env.WORKBUDDY_AI_HOME, home) || path.join(home, ".workbuddy-ai");
|
|
177
|
+
out.push(buildEntry({
|
|
178
|
+
name: "workbuddy-ai",
|
|
179
|
+
hookExpected: true,
|
|
180
|
+
hookInstalled: Boolean(hookStatus?.["workbuddy-ai"]),
|
|
181
|
+
logsDir: workbuddyAiHome,
|
|
182
|
+
logsPredicate: (_full, name) => name === "projects" || name.endsWith(".jsonl"),
|
|
183
|
+
settingsPath: path.join(workbuddyAiHome, "settings.json"),
|
|
184
|
+
}));
|
|
185
|
+
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function buildEntry({ name, hookExpected, hookInstalled, logsDir, logsPredicate, settingsPath }) {
|
|
190
|
+
const logsPresent = dirHasFile(logsDir, logsPredicate);
|
|
191
|
+
const passive = hookExpected && !hookInstalled && logsPresent;
|
|
192
|
+
let reason = null;
|
|
193
|
+
if (hookExpected && !hookInstalled) {
|
|
194
|
+
reason = classifyWritableFailure(settingsPath);
|
|
195
|
+
}
|
|
196
|
+
return {
|
|
197
|
+
name,
|
|
198
|
+
hook_expected: hookExpected,
|
|
199
|
+
hook_installed: hookInstalled,
|
|
200
|
+
logs_present: logsPresent,
|
|
201
|
+
passive,
|
|
202
|
+
hook_failure_reason: reason,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Convenience boolean: is at least one provider in passive mode?
|
|
208
|
+
*/
|
|
209
|
+
function isPassiveModeActive(providers) {
|
|
210
|
+
return providers.some((p) => p.passive);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
module.exports = {
|
|
214
|
+
detectPassiveProviders,
|
|
215
|
+
isPassiveModeActive,
|
|
216
|
+
// Exposed for unit testing
|
|
217
|
+
dirHasFile,
|
|
218
|
+
classifyWritableFailure,
|
|
219
|
+
};
|