tokenusage-cli 0.4.6 → 0.5.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 +111 -115
- package/README.md +88 -21
- package/package.json +1 -1
- package/src/cli.js +1 -0
- package/src/commands/doctor.js +3 -0
- package/src/commands/init.js +20 -2
- package/src/commands/reconcile.js +5 -0
- package/src/commands/status.js +16 -0
- package/src/commands/sync.js +125 -27
- package/src/commands/upload.js +4 -0
- package/src/lib/device-identity.js +84 -0
- package/src/lib/doctor.js +32 -2
- package/src/lib/pricing/index.js +1 -1
- package/src/lib/pricing/seed-snapshot.json +1 -1
- package/src/lib/pricing-coverage.js +1 -1
- package/src/lib/progress.js +29 -0
- package/src/lib/project-repos.js +259 -0
- package/src/lib/rollout.js +63 -4
|
@@ -43,6 +43,7 @@ const { sanitizeBucketForUpload } = require("../lib/ingest-sanitize");
|
|
|
43
43
|
const { basenameKey } = require("../lib/project-key");
|
|
44
44
|
const { TOKEN_COLUMNS } = require("../lib/account-usage-dedup");
|
|
45
45
|
const { UsageError, unknownOptionError } = require("../lib/cli-errors");
|
|
46
|
+
const { buildDeviceIdentity } = require("../lib/device-identity");
|
|
46
47
|
|
|
47
48
|
const RECONCILE_SLUG = "token-usage-reconcile";
|
|
48
49
|
const DAY_MS = 86_400_000;
|
|
@@ -440,6 +441,7 @@ function renderText(summary) {
|
|
|
440
441
|
pendingCount > 0
|
|
441
442
|
? ` ${pendingCount.toLocaleString("en-US")} of them are past the upload offset (queue.state.json) and not compared yet`
|
|
442
443
|
: null,
|
|
444
|
+
`Local device: ${summary.device_name || "unknown machine"}${summary.machine_id ? ` (machine ${summary.machine_id.slice(0, 8)})` : ""}`,
|
|
443
445
|
`Cloud device: ${summary.device_id || "unknown"} — ${summary.cloud_buckets.toLocaleString("en-US")} row(s) in ${summary.pages} page(s)`,
|
|
444
446
|
].filter(Boolean);
|
|
445
447
|
|
|
@@ -506,6 +508,7 @@ async function cmdReconcile(argv = [], options = {}) {
|
|
|
506
508
|
|
|
507
509
|
const config = (await readJson(path.join(trackerDir, "config.json"))) || {};
|
|
508
510
|
const runtime = assertInsforgeRuntime(resolveRuntimeConfig({ config, env: process.env }));
|
|
511
|
+
const deviceIdentity = buildDeviceIdentity({ config, hostname: os.hostname() });
|
|
509
512
|
if (!runtime.deviceToken) {
|
|
510
513
|
throw new UsageError("This machine is not paired with a dashboard yet.", {
|
|
511
514
|
code: "NO_DEVICE_TOKEN",
|
|
@@ -542,6 +545,8 @@ async function cmdReconcile(argv = [], options = {}) {
|
|
|
542
545
|
to,
|
|
543
546
|
clamped: window.clamped,
|
|
544
547
|
device_id: deviceId,
|
|
548
|
+
device_name: deviceIdentity.name,
|
|
549
|
+
machine_id: deviceIdentity.machine_id,
|
|
545
550
|
local_buckets: local.size,
|
|
546
551
|
cloud_buckets: server.size,
|
|
547
552
|
pages,
|
package/src/commands/status.js
CHANGED
|
@@ -49,6 +49,8 @@ const {
|
|
|
49
49
|
} = require("../lib/openclaw-session-plugin");
|
|
50
50
|
const { resolveTrackerPaths } = require("../lib/tracker-paths");
|
|
51
51
|
const { resolveDeviceTokenPresence } = require("../lib/cloud-device-token");
|
|
52
|
+
const { resolveLocalDeviceIdentity } = require("../lib/device-identity");
|
|
53
|
+
const { formatDeviceLine } = require("../lib/progress");
|
|
52
54
|
const { getPricingMeta } = require("../lib/pricing");
|
|
53
55
|
const {
|
|
54
56
|
isCollectionPaused,
|
|
@@ -1073,12 +1075,22 @@ async function cmdStatus(argv = []) {
|
|
|
1073
1075
|
config: config || {},
|
|
1074
1076
|
});
|
|
1075
1077
|
|
|
1078
|
+
// Which collector machine is this? Two machines report into one account, so
|
|
1079
|
+
// every status output has to name itself — see lib/device-identity.js.
|
|
1080
|
+
const deviceIdentity = resolveLocalDeviceIdentity({ config: config || {}, home });
|
|
1081
|
+
|
|
1076
1082
|
if (opts.json || opts.light) {
|
|
1077
1083
|
const summary = {
|
|
1078
1084
|
version: pkg.version,
|
|
1079
1085
|
generated_at: new Date().toISOString(),
|
|
1080
1086
|
base_url: config?.baseUrl || null,
|
|
1081
1087
|
device_token_set: deviceTokenPresence.set,
|
|
1088
|
+
device: {
|
|
1089
|
+
name: deviceIdentity.name,
|
|
1090
|
+
hostname: deviceIdentity.hostname,
|
|
1091
|
+
machine_id: deviceIdentity.machine_id,
|
|
1092
|
+
device_id: deviceIdentity.device_id,
|
|
1093
|
+
},
|
|
1082
1094
|
queue: {
|
|
1083
1095
|
pending_bytes: pendingBytes,
|
|
1084
1096
|
size_bytes: queueSize,
|
|
@@ -1316,6 +1328,7 @@ async function cmdStatus(argv = []) {
|
|
|
1316
1328
|
"Status:",
|
|
1317
1329
|
`- Base URL: ${config?.baseUrl || "unset"}`,
|
|
1318
1330
|
`- Device token: ${deviceTokenPresence.set ? "set" : "unset"}`,
|
|
1331
|
+
formatDeviceLine(deviceIdentity),
|
|
1319
1332
|
collectionPaused
|
|
1320
1333
|
? "- Collection: PAUSED (auto/notify/watch syncs skip; manual sync runs; `tokenusage resume` to re-enable)"
|
|
1321
1334
|
: "- Collection: active",
|
|
@@ -1751,6 +1764,8 @@ function renderLightTable(summary) {
|
|
|
1751
1764
|
push("Version", summary.version);
|
|
1752
1765
|
push("Base URL", summary.base_url);
|
|
1753
1766
|
push("Device token", summary.device_token_set ? "set" : "unset");
|
|
1767
|
+
push("Device", summary.device?.name);
|
|
1768
|
+
push("Device ID", summary.device?.device_id);
|
|
1754
1769
|
push("Queue pending (bytes)", summary.queue.pending_bytes);
|
|
1755
1770
|
push("Queue size (bytes)", summary.queue.size_bytes);
|
|
1756
1771
|
push("Last parse", summary.last_parse);
|
|
@@ -1887,5 +1902,6 @@ module.exports = {
|
|
|
1887
1902
|
cmdStatus,
|
|
1888
1903
|
formatUsageLimitRows,
|
|
1889
1904
|
parseArgs,
|
|
1905
|
+
renderLightTable,
|
|
1890
1906
|
summarizeQoderDetail,
|
|
1891
1907
|
};
|
package/src/commands/sync.js
CHANGED
|
@@ -158,7 +158,8 @@ const {
|
|
|
158
158
|
resolveZcodeInstallPaths,
|
|
159
159
|
} = require("../lib/rollout");
|
|
160
160
|
const { computeClaudeGroundTruthBuckets } = require("../lib/claude-categorizer");
|
|
161
|
-
const { createProgress, renderBar, formatNumber, formatBytes } = require("../lib/progress");
|
|
161
|
+
const { createProgress, renderBar, formatNumber, formatBytes, formatDuration, formatDeviceLine } = require("../lib/progress");
|
|
162
|
+
const { buildDeviceIdentity } = require("../lib/device-identity");
|
|
162
163
|
const {
|
|
163
164
|
DEFAULTS: AUTO_UPLOAD_DEFAULTS,
|
|
164
165
|
normalizeState: normalizeUploadState,
|
|
@@ -572,6 +573,58 @@ async function clearSyncSkip(trackerDir) {
|
|
|
572
573
|
}
|
|
573
574
|
}
|
|
574
575
|
|
|
576
|
+
/**
|
|
577
|
+
* The human summary of one sync run.
|
|
578
|
+
*
|
|
579
|
+
* Pure on purpose: the summary is what ends up pasted into runbooks and issue
|
|
580
|
+
* trackers, so it has to state WHICH machine ran, how much was uploaded (in
|
|
581
|
+
* tokens, not just rows), how many sessions moved, what is still pending and
|
|
582
|
+
* how long it took. Extracted from cmdSync so it can be unit-tested.
|
|
583
|
+
*/
|
|
584
|
+
function buildSyncSummaryLines({
|
|
585
|
+
deviceIdentity = null,
|
|
586
|
+
totalParsed = 0,
|
|
587
|
+
totalBuckets = 0,
|
|
588
|
+
uploadResult = {},
|
|
589
|
+
sessionUploadSummary = null,
|
|
590
|
+
hasDeviceToken = false,
|
|
591
|
+
pendingBytes = 0,
|
|
592
|
+
drain = false,
|
|
593
|
+
durationMs = 0,
|
|
594
|
+
uploadError = null,
|
|
595
|
+
warning = null,
|
|
596
|
+
} = {}) {
|
|
597
|
+
const uploadedTokens = Number(uploadResult.tokens || 0);
|
|
598
|
+
const uploadedCredits = Number(uploadResult.credits || 0);
|
|
599
|
+
const inserted = Number(uploadResult.inserted || 0);
|
|
600
|
+
const rowWord = inserted === 1 ? "row" : "rows";
|
|
601
|
+
const lines = ["Sync finished:"];
|
|
602
|
+
if (deviceIdentity) lines.push(formatDeviceLine(deviceIdentity));
|
|
603
|
+
lines.push(
|
|
604
|
+
`- Parsed files: ${formatNumber(totalParsed)}`,
|
|
605
|
+
`- New 30-min buckets queued: ${formatNumber(totalBuckets)}`,
|
|
606
|
+
hasDeviceToken
|
|
607
|
+
? `- Uploaded: ${formatNumber(inserted)} ${rowWord} (${formatNumber(uploadedTokens)} tokens), ${formatNumber(uploadResult.skipped)} skipped`
|
|
608
|
+
: "- Uploaded: skipped (no device token)",
|
|
609
|
+
);
|
|
610
|
+
if (hasDeviceToken && uploadedCredits > 0) {
|
|
611
|
+
lines.push(`- Credits: ${formatNumber(uploadedCredits)}`);
|
|
612
|
+
}
|
|
613
|
+
if (sessionUploadSummary) {
|
|
614
|
+
lines.push(
|
|
615
|
+
`- Sessions: ${formatNumber(sessionUploadSummary.uploaded)}/${formatNumber(sessionUploadSummary.pending)} uploaded (upserted ${formatNumber(sessionUploadSummary.upserted)}, skipped ${formatNumber(sessionUploadSummary.skipped)})`,
|
|
616
|
+
);
|
|
617
|
+
}
|
|
618
|
+
if (hasDeviceToken && pendingBytes > 0 && !drain) {
|
|
619
|
+
lines.push(`- Remaining: ${formatBytes(pendingBytes)} pending (run sync again, or use --drain)`);
|
|
620
|
+
}
|
|
621
|
+
lines.push(`- Duration: ${formatDuration(durationMs)}`);
|
|
622
|
+
if (uploadError) lines.push(`- Upload error: ${uploadError.message || uploadError}`);
|
|
623
|
+
if (warning) lines.push(`- Warning: ${warning}`);
|
|
624
|
+
lines.push("");
|
|
625
|
+
return lines;
|
|
626
|
+
}
|
|
627
|
+
|
|
575
628
|
async function cmdSync(argv, context = {}) {
|
|
576
629
|
context = context && typeof context === "object" ? context : {};
|
|
577
630
|
const opts = parseArgs(argv);
|
|
@@ -597,6 +650,8 @@ async function cmdSync(argv, context = {}) {
|
|
|
597
650
|
const syncDiagnostics = diagnostics && typeof diagnostics === "object" ? diagnostics : null;
|
|
598
651
|
const home = context.home || os.homedir();
|
|
599
652
|
const trackerDir = context.trackerDataDir || (await resolveTrackerPaths({ home })).trackerDir;
|
|
653
|
+
// Wall clock for the run summary (the §2.11 run record keeps its own).
|
|
654
|
+
const syncStartedAtMs = Date.now();
|
|
600
655
|
// Collection pause (0.2.0): auto-flavored runs exit silently — no lock, no
|
|
601
656
|
// log line, no run record. A manual sync is the user's explicit request
|
|
602
657
|
// and runs regardless of the flag.
|
|
@@ -3641,6 +3696,9 @@ async function cmdSync(argv, context = {}) {
|
|
|
3641
3696
|
let uploadAttempted = false;
|
|
3642
3697
|
let uploadError = null;
|
|
3643
3698
|
let autoUploadDecision = null;
|
|
3699
|
+
// Session upload counters, folded into the final summary instead of being
|
|
3700
|
+
// printed on their own line before it.
|
|
3701
|
+
let sessionUploadSummary = null;
|
|
3644
3702
|
|
|
3645
3703
|
if (canUpload() && (opts.auto || opts.publishAccount) && runtime.deviceToken && runtime.baseUrl &&
|
|
3646
3704
|
(!isBackgroundLightweightSync || opts.publishAccount)) {
|
|
@@ -3831,17 +3889,21 @@ async function cmdSync(argv, context = {}) {
|
|
|
3831
3889
|
canUpload,
|
|
3832
3890
|
});
|
|
3833
3891
|
if (result.pending > 0) {
|
|
3834
|
-
|
|
3835
|
-
|
|
3836
|
-
|
|
3837
|
-
|
|
3838
|
-
|
|
3839
|
-
|
|
3840
|
-
|
|
3841
|
-
|
|
3842
|
-
|
|
3843
|
-
|
|
3844
|
-
|
|
3892
|
+
sessionUploadSummary = {
|
|
3893
|
+
uploaded: result.uploaded,
|
|
3894
|
+
pending: result.pending,
|
|
3895
|
+
upserted: result.upserted,
|
|
3896
|
+
skipped: (result.skippedServer || 0) + (result.skippedLocal || 0),
|
|
3897
|
+
};
|
|
3898
|
+
// Auto runs keep the rolling log line; a manual run reports the same
|
|
3899
|
+
// counters inside the final summary block (printing here would put
|
|
3900
|
+
// the sessions line above the summary it belongs to).
|
|
3901
|
+
if (opts.auto) {
|
|
3902
|
+
const sessionSuffix =
|
|
3903
|
+
result.upserted || result.skippedServer
|
|
3904
|
+
? ` (upserted ${result.upserted}, skipped ${result.skippedServer})`
|
|
3905
|
+
: "";
|
|
3906
|
+
autoLog(`Sessions: ${result.uploaded}/${result.pending} uploaded${sessionSuffix}`);
|
|
3845
3907
|
}
|
|
3846
3908
|
}
|
|
3847
3909
|
syncRun?.noteSessions({
|
|
@@ -3871,6 +3933,35 @@ async function cmdSync(argv, context = {}) {
|
|
|
3871
3933
|
}
|
|
3872
3934
|
}
|
|
3873
3935
|
|
|
3936
|
+
// Detected project repositories (docs/cli-contract.md §2.4 `projects`,
|
|
3937
|
+
// contract v3). Best-effort like sessions: repo metadata never fails a run.
|
|
3938
|
+
// A backend that predates v3 answers the projects-only request with 400 or
|
|
3939
|
+
// 404/405; those entries simply stay pending until the server is upgraded.
|
|
3940
|
+
if (canUpload() && runtime.deviceToken && runtime.baseUrl &&
|
|
3941
|
+
(!isBackgroundLightweightSync || opts.publishAccount)) {
|
|
3942
|
+
try {
|
|
3943
|
+
const repoResult = await uploadProjectRepos({
|
|
3944
|
+
baseUrl: runtime.baseUrl,
|
|
3945
|
+
anonKey: runtime.anonKey,
|
|
3946
|
+
deviceToken: runtime.deviceToken,
|
|
3947
|
+
projects: cursors?.projectHourly?.projects || {},
|
|
3948
|
+
statePath: path.join(trackerDir, "project.repos.state.json"),
|
|
3949
|
+
canUpload,
|
|
3950
|
+
});
|
|
3951
|
+
if (repoResult.uploaded > 0 && opts.auto) {
|
|
3952
|
+
autoLog(`Project repos: ${repoResult.uploaded} updated`);
|
|
3953
|
+
}
|
|
3954
|
+
} catch (repoError) {
|
|
3955
|
+
// Auxiliary metadata: log, leave the confirmed state untouched so the
|
|
3956
|
+
// next sync retries, and keep the run's outcome unchanged.
|
|
3957
|
+
autoLog(`Project repo upload error: ${repoError?.message || repoError}`, {
|
|
3958
|
+
phase: "project-repos",
|
|
3959
|
+
error: String(repoError?.message || repoError),
|
|
3960
|
+
status: Number.isInteger(repoError?.status) ? repoError.status : null,
|
|
3961
|
+
});
|
|
3962
|
+
}
|
|
3963
|
+
}
|
|
3964
|
+
|
|
3874
3965
|
const afterState = (await readJson(queueStatePath)) || { offset: 0 };
|
|
3875
3966
|
const queueSize = await safeStatSize(queuePath);
|
|
3876
3967
|
// Only the main queue is uploaded by drainQueueToCloud. project.queue.jsonl
|
|
@@ -3904,28 +3995,28 @@ async function cmdSync(argv, context = {}) {
|
|
|
3904
3995
|
|
|
3905
3996
|
if (!autoishSync) {
|
|
3906
3997
|
const codexRecordOnlyWarning = formatRecordOnlyWarning(countRecordOnlyFiles(cursors));
|
|
3998
|
+
const deviceIdentity = buildDeviceIdentity({ config: runtimeConfig, hostname: os.hostname() });
|
|
3907
3999
|
process.stdout.write(
|
|
3908
|
-
|
|
3909
|
-
|
|
3910
|
-
|
|
3911
|
-
|
|
3912
|
-
|
|
3913
|
-
|
|
3914
|
-
|
|
3915
|
-
|
|
3916
|
-
|
|
3917
|
-
|
|
3918
|
-
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
.filter(Boolean)
|
|
3922
|
-
.join("\n"),
|
|
4000
|
+
buildSyncSummaryLines({
|
|
4001
|
+
deviceIdentity,
|
|
4002
|
+
totalParsed,
|
|
4003
|
+
totalBuckets,
|
|
4004
|
+
uploadResult,
|
|
4005
|
+
sessionUploadSummary,
|
|
4006
|
+
hasDeviceToken: Boolean(runtime.deviceToken),
|
|
4007
|
+
pendingBytes,
|
|
4008
|
+
drain: Boolean(opts.drain),
|
|
4009
|
+
durationMs: Date.now() - syncStartedAtMs,
|
|
4010
|
+
uploadError,
|
|
4011
|
+
warning: codexRecordOnlyWarning,
|
|
4012
|
+
}).join("\n"),
|
|
3923
4013
|
);
|
|
3924
4014
|
} else {
|
|
3925
4015
|
autoLog(
|
|
3926
4016
|
`Auto sync finished — parsed ${totalParsed} files, +${totalBuckets} buckets, ` +
|
|
3927
4017
|
(runtime.deviceToken
|
|
3928
4018
|
? `uploaded ${uploadResult.inserted}, skipped ${uploadResult.skipped}` +
|
|
4019
|
+
`, ${uploadResult.tokens || 0} tokens` +
|
|
3929
4020
|
(pendingBytes > 0 ? `, pending ${formatBytes(pendingBytes)}` : ", queue drained")
|
|
3930
4021
|
: "upload skipped (no device token)"),
|
|
3931
4022
|
{
|
|
@@ -3934,7 +4025,12 @@ async function cmdSync(argv, context = {}) {
|
|
|
3934
4025
|
buckets: totalBuckets,
|
|
3935
4026
|
inserted: uploadResult.inserted,
|
|
3936
4027
|
skipped: uploadResult.skipped,
|
|
4028
|
+
tokens: uploadResult.tokens || 0,
|
|
4029
|
+
credits: uploadResult.credits || 0,
|
|
4030
|
+
sessions_uploaded: sessionUploadSummary ? sessionUploadSummary.uploaded : 0,
|
|
4031
|
+
sessions_skipped: sessionUploadSummary ? sessionUploadSummary.skipped : 0,
|
|
3937
4032
|
pending_bytes: pendingBytes,
|
|
4033
|
+
duration_ms: Date.now() - syncStartedAtMs,
|
|
3938
4034
|
uploaded: Boolean(runtime.deviceToken),
|
|
3939
4035
|
},
|
|
3940
4036
|
);
|
|
@@ -4112,6 +4208,7 @@ function recordCodexColdScanAudit(
|
|
|
4112
4208
|
module.exports = {
|
|
4113
4209
|
cmdSync,
|
|
4114
4210
|
acquireSyncLock,
|
|
4211
|
+
buildSyncSummaryLines,
|
|
4115
4212
|
readQueueBatch,
|
|
4116
4213
|
drainQueueToCloud,
|
|
4117
4214
|
normalizeSyncSource,
|
|
@@ -4646,6 +4743,7 @@ const AUTO_RETRY_MAX_DELAY_MS = 2 * 60 * 60 * 1000;
|
|
|
4646
4743
|
const INGEST_SLUG = "token-usage-ingest";
|
|
4647
4744
|
const { buildSessionAnalytics } = require("../lib/session-analytics");
|
|
4648
4745
|
const { uploadSessions } = require("../lib/session-upload");
|
|
4746
|
+
const { uploadProjectRepos } = require("../lib/project-repos");
|
|
4649
4747
|
const MAX_INGEST_BUCKETS = 500;
|
|
4650
4748
|
|
|
4651
4749
|
async function drainQueueToCloud({ baseUrl, anonKey, deviceToken, queuePath, queueStatePath, maxBatches = 5, batchSize = 200, maxDurationMs = UPLOAD_BUDGET_MS, canUpload = () => true }) {
|
package/src/commands/upload.js
CHANGED
|
@@ -18,6 +18,8 @@ const path = require("node:path");
|
|
|
18
18
|
const fs = require("node:fs/promises");
|
|
19
19
|
|
|
20
20
|
const { resolveTrackerPaths } = require("../lib/tracker-paths");
|
|
21
|
+
const { formatDeviceLine } = require("../lib/progress");
|
|
22
|
+
const { buildDeviceIdentity } = require("../lib/device-identity");
|
|
21
23
|
const { readJson } = require("../lib/fs");
|
|
22
24
|
const { cloudUsageResetBlocksUpload } = require("../lib/cloud-usage-reset");
|
|
23
25
|
const { compactPendingQueue } = require("../lib/upload-queue");
|
|
@@ -134,9 +136,11 @@ async function cmdUpload(argv, options = {}) {
|
|
|
134
136
|
process.stdout.write(
|
|
135
137
|
[
|
|
136
138
|
"Upload complete.",
|
|
139
|
+
formatDeviceLine(buildDeviceIdentity({ config, hostname: os.hostname() })),
|
|
137
140
|
`- Requests: ${result.batches}`,
|
|
138
141
|
`- Rows inserted: ${result.inserted.toLocaleString("en-US")} (skipped ${result.skipped.toLocaleString("en-US")})`,
|
|
139
142
|
`- Tokens in this upload: ${result.tokens.toLocaleString("en-US")}`,
|
|
143
|
+
result.credits > 0 ? `- Credits in this upload: ${result.credits.toLocaleString("en-US")}` : null,
|
|
140
144
|
`- Pending bytes: ${beforeBytes} → ${afterBytes}`,
|
|
141
145
|
afterBytes > 0 ? "- Backlog remains; run `tokenusage upload --drain` or retry later." : null,
|
|
142
146
|
"",
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const os = require("node:os");
|
|
5
|
+
const path = require("node:path");
|
|
6
|
+
|
|
7
|
+
// Hostname fallback — the contract (§2.2) uses this when client_info carries
|
|
8
|
+
// no hostname, so the cloud device name stays `<host> #<machine_id[:8]>`.
|
|
9
|
+
const FALLBACK_DEVICE_NAME = "Token Usage CLI";
|
|
10
|
+
|
|
11
|
+
function trimmedString(value) {
|
|
12
|
+
return typeof value === "string" && value.trim() ? value.trim() : "";
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function readSeedMachineId(seedPath) {
|
|
16
|
+
try {
|
|
17
|
+
return trimmedString(fs.readFileSync(seedPath, "utf8"));
|
|
18
|
+
} catch {
|
|
19
|
+
return "";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function defaultSeedPath(home = os.homedir()) {
|
|
24
|
+
return path.join(home, ".config", "tokenusage", "machine-id");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* This machine's cloud device identity.
|
|
29
|
+
*
|
|
30
|
+
* The device name is defined by docs/cli-contract.md §2.2:
|
|
31
|
+
* `<client_info hostname> #<machine_id first 8 chars>`
|
|
32
|
+
* — client_info without a hostname falls back to "Token Usage CLI", a missing
|
|
33
|
+
* machine_id drops the suffix. The cloud derives it the same way from the
|
|
34
|
+
* `client_info` / `machine_id` the CLI sends at device-flow time, so the name
|
|
35
|
+
* computed here matches the dashboard's device card byte for byte.
|
|
36
|
+
*
|
|
37
|
+
* Why the CLI bothers to print it: two collector machines report into one
|
|
38
|
+
* account, and `status` output is what gets pasted into issue trackers and
|
|
39
|
+
* release checklists. Without the identity in the output, a reader cannot tell
|
|
40
|
+
* which machine produced a number — that is how "this machine" and "the other
|
|
41
|
+
* machine" got mixed up in the docs.
|
|
42
|
+
*
|
|
43
|
+
* Read-only on purpose: unlike getOrCreateMachineId() this never mints or
|
|
44
|
+
* persists an id, so `status` stays a safe command to run anywhere.
|
|
45
|
+
*/
|
|
46
|
+
function buildDeviceIdentity({
|
|
47
|
+
config = {},
|
|
48
|
+
hostname = os.hostname(),
|
|
49
|
+
seedPath = null,
|
|
50
|
+
home = os.homedir(),
|
|
51
|
+
} = {}) {
|
|
52
|
+
const machineId =
|
|
53
|
+
trimmedString(config.machineId) || (seedPath ? readSeedMachineId(seedPath) : "");
|
|
54
|
+
const deviceId = trimmedString(config.deviceId);
|
|
55
|
+
const host = trimmedString(hostname) || FALLBACK_DEVICE_NAME;
|
|
56
|
+
const suffix = machineId ? machineId.slice(0, 8) : "";
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
name: suffix ? `${host} #${suffix}` : host,
|
|
60
|
+
hostname: host,
|
|
61
|
+
machine_id: machineId || null,
|
|
62
|
+
device_id: deviceId || null,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Identity of the machine this CLI runs on, reading the tracker config plus
|
|
68
|
+
* the purge-surviving identity seed (so `status` still names the device after
|
|
69
|
+
* a `uninstall --purge` wiped ~/.tokenusage).
|
|
70
|
+
*/
|
|
71
|
+
function resolveLocalDeviceIdentity({ config = {}, home = os.homedir() } = {}) {
|
|
72
|
+
return buildDeviceIdentity({
|
|
73
|
+
config,
|
|
74
|
+
hostname: os.hostname(),
|
|
75
|
+
seedPath: defaultSeedPath(home),
|
|
76
|
+
home,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = {
|
|
81
|
+
FALLBACK_DEVICE_NAME,
|
|
82
|
+
buildDeviceIdentity,
|
|
83
|
+
resolveLocalDeviceIdentity,
|
|
84
|
+
};
|
package/src/lib/doctor.js
CHANGED
|
@@ -10,11 +10,13 @@ async function buildDoctorReport({
|
|
|
10
10
|
diagnostics = null,
|
|
11
11
|
fetch = globalThis.fetch,
|
|
12
12
|
now = () => new Date(),
|
|
13
|
+
deviceIdentity = null,
|
|
13
14
|
paths = {},
|
|
14
15
|
} = {}) {
|
|
15
16
|
const checks = [];
|
|
16
17
|
|
|
17
18
|
checks.push(...buildRuntimeChecks(runtime));
|
|
19
|
+
checks.push(...buildDeviceIdentityChecks(deviceIdentity));
|
|
18
20
|
|
|
19
21
|
if (paths.trackerDir) {
|
|
20
22
|
checks.push(await checkTrackerDir(paths.trackerDir));
|
|
@@ -131,6 +133,34 @@ function buildRuntimeChecks(runtime = {}) {
|
|
|
131
133
|
return checks;
|
|
132
134
|
}
|
|
133
135
|
|
|
136
|
+
/**
|
|
137
|
+
* Which collector machine is this? The account has two of them, and every
|
|
138
|
+
* doctor report gets pasted into release checklists — without the device
|
|
139
|
+
* identity in the report, a reader cannot tell the two apart.
|
|
140
|
+
*/
|
|
141
|
+
function buildDeviceIdentityChecks(deviceIdentity) {
|
|
142
|
+
const checks = [];
|
|
143
|
+
if (!deviceIdentity) return checks;
|
|
144
|
+
|
|
145
|
+
const machineId = deviceIdentity.machine_id || null;
|
|
146
|
+
checks.push({
|
|
147
|
+
id: "runtime.device_identity",
|
|
148
|
+
status: machineId ? "ok" : "warn",
|
|
149
|
+
detail: machineId
|
|
150
|
+
? `device ${deviceIdentity.name} (id ${deviceIdentity.device_id || "unpaired"})`
|
|
151
|
+
: `device ${deviceIdentity.name} (machine_id missing)`,
|
|
152
|
+
critical: false,
|
|
153
|
+
meta: {
|
|
154
|
+
name: deviceIdentity.name || null,
|
|
155
|
+
hostname: deviceIdentity.hostname || null,
|
|
156
|
+
machine_id: machineId,
|
|
157
|
+
device_id: deviceIdentity.device_id || null,
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
return checks;
|
|
162
|
+
}
|
|
163
|
+
|
|
134
164
|
async function checkTrackerDir(trackerDir) {
|
|
135
165
|
try {
|
|
136
166
|
const st = await fs.stat(trackerDir);
|
|
@@ -180,7 +210,7 @@ async function checkTrackerDir(trackerDir) {
|
|
|
180
210
|
}
|
|
181
211
|
}
|
|
182
212
|
|
|
183
|
-
// B3 (docs/upstream-
|
|
213
|
+
// B3 (docs/archive/upstream-2026-11-03.md): pricing coverage of the local
|
|
184
214
|
// last-wins queue over the trailing 7 days, plus the C2 unknown-alignment
|
|
185
215
|
// dry-run preview. Informational only — never critical, never writes.
|
|
186
216
|
async function checkPricingCoverage(trackerDir) {
|
|
@@ -502,4 +532,4 @@ function summarizeChecks(checks = []) {
|
|
|
502
532
|
return summary;
|
|
503
533
|
}
|
|
504
534
|
|
|
505
|
-
module.exports = { buildDoctorReport };
|
|
535
|
+
module.exports = { buildDoctorReport, buildDeviceIdentityChecks };
|
package/src/lib/pricing/index.js
CHANGED
|
@@ -113,7 +113,7 @@ function getPricingRevision() {
|
|
|
113
113
|
|
|
114
114
|
// Read-only snapshot of where pricing data came from and how stale it is.
|
|
115
115
|
// Surfaced by `status --json` so a $0 cost can be triaged as "not collected"
|
|
116
|
-
// vs "not priced" without digging into cache files (docs/upstream-
|
|
116
|
+
// vs "not priced" without digging into cache files (docs/archive/upstream-2026-11-03.md A3).
|
|
117
117
|
function getPricingMeta() {
|
|
118
118
|
return {
|
|
119
119
|
source: state.source,
|