tokenusage-cli 0.5.0 → 0.5.1
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 +16 -0
- package/package.json +1 -1
- package/src/commands/doctor.js +15 -0
- package/src/lib/doctor.js +55 -0
- package/src/lib/scheduled-task.js +166 -28
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,22 @@
|
|
|
6
6
|
> 0.4.x 之前的条目为压缩摘要;细节与当时的验收记录见 `docs/cli-release.md`
|
|
7
7
|
> 与 `docs/archive/`。
|
|
8
8
|
|
|
9
|
+
## 0.5.1
|
|
10
|
+
|
|
11
|
+
2026-11-06。修复 Windows 计划任务在非提升权限安装下的静默降级 + `doctor` 新增计划任务自检。
|
|
12
|
+
零契约变更,服务端无需同步升级。
|
|
13
|
+
|
|
14
|
+
- **修复 Windows 计划任务注册**:`<LogonTrigger>` 缺少 `<UserId>` 时 `schtasks` 按「任意用户」解析,
|
|
15
|
+
非提升权限的 `/Create /XML` 直接返回 `Access is denied`,整份定义被丢弃、退回纯 `-SC HOURLY`
|
|
16
|
+
——丢掉 `StartWhenAvailable` 睡眠后补跑、登录补采、失败重试与无限运行时长。现在登录触发写入
|
|
17
|
+
当前用户;注册失败时先重试「无登录触发」的完整定义(保留补跑/重试/无限时长),再不行才退回
|
|
18
|
+
纯每小时,摘要按原因区分 `logon_trigger_rejected` 与 `xml_rejected`。
|
|
19
|
+
- **`doctor` 新增 `schedule.registered` 自检**:读取已注册的计划任务(Windows 用
|
|
20
|
+
`schtasks /Query /XML`,macOS/Linux 检查 launchd plist / systemd timer),发现降级定义或未注册
|
|
21
|
+
直接告警并提示重跑 `tokenusage init`;检查项从 16 项增至 17 项。
|
|
22
|
+
- **升级提示**:0.5.0 在 Windows 上装过的机器升级后重跑一次 `tokenusage init --yes`,让计划任务
|
|
23
|
+
换成带当前用户的完整定义,再用 `doctor` 确认。
|
|
24
|
+
|
|
9
25
|
## 0.5.0
|
|
10
26
|
|
|
11
27
|
2026-11-06。定价数据刷新 + WorkBuddy 项目归属 + 仓库地址上报(契约 v3)。服务端需先部署项目仓库
|
package/package.json
CHANGED
package/src/commands/doctor.js
CHANGED
|
@@ -8,6 +8,7 @@ const { resolveRuntimeConfig } = require("../lib/runtime-config");
|
|
|
8
8
|
const { resolveDeviceTokenPresence } = require("../lib/cloud-device-token");
|
|
9
9
|
const { resolveLocalDeviceIdentity } = require("../lib/device-identity");
|
|
10
10
|
const { buildDoctorReport } = require("../lib/doctor");
|
|
11
|
+
const { inspectAutoSyncSchedule } = require("../lib/scheduled-task");
|
|
11
12
|
|
|
12
13
|
async function cmdDoctor(argv = []) {
|
|
13
14
|
const opts = parseArgs(argv);
|
|
@@ -39,12 +40,26 @@ async function cmdDoctor(argv = []) {
|
|
|
39
40
|
const diagnostics = await collectTrackerDiagnostics({ home });
|
|
40
41
|
const cliPath = process.argv[1] ? path.resolve(process.argv[1]) : null;
|
|
41
42
|
const deviceIdentity = resolveLocalDeviceIdentity({ config, home });
|
|
43
|
+
// Never let a scheduler probe failure take the whole report down: a broken
|
|
44
|
+
// schedule is exactly the state doctor should be able to describe.
|
|
45
|
+
let schedule = null;
|
|
46
|
+
try {
|
|
47
|
+
schedule = inspectAutoSyncSchedule({ home });
|
|
48
|
+
} catch (error) {
|
|
49
|
+
schedule = {
|
|
50
|
+
platform: process.platform,
|
|
51
|
+
label: "Scheduled sync",
|
|
52
|
+
state: "missing",
|
|
53
|
+
detail: String(error?.message || error),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
42
56
|
|
|
43
57
|
const report = await buildDoctorReport({
|
|
44
58
|
runtime,
|
|
45
59
|
diagnostics,
|
|
46
60
|
fetch: globalThis.fetch,
|
|
47
61
|
deviceIdentity,
|
|
62
|
+
schedule,
|
|
48
63
|
paths: {
|
|
49
64
|
trackerDir,
|
|
50
65
|
configPath,
|
package/src/lib/doctor.js
CHANGED
|
@@ -11,6 +11,7 @@ async function buildDoctorReport({
|
|
|
11
11
|
fetch = globalThis.fetch,
|
|
12
12
|
now = () => new Date(),
|
|
13
13
|
deviceIdentity = null,
|
|
14
|
+
schedule = null,
|
|
14
15
|
paths = {},
|
|
15
16
|
} = {}) {
|
|
16
17
|
const checks = [];
|
|
@@ -29,6 +30,9 @@ async function buildDoctorReport({
|
|
|
29
30
|
if (paths.cliPath) {
|
|
30
31
|
checks.push(await checkCliEntrypoint(paths.cliPath));
|
|
31
32
|
}
|
|
33
|
+
if (schedule) {
|
|
34
|
+
checks.push(buildScheduleCheck(schedule));
|
|
35
|
+
}
|
|
32
36
|
|
|
33
37
|
checks.push(await checkNetwork({ baseUrl: runtime?.baseUrl || null, fetch }));
|
|
34
38
|
|
|
@@ -161,6 +165,57 @@ function buildDeviceIdentityChecks(deviceIdentity) {
|
|
|
161
165
|
return checks;
|
|
162
166
|
}
|
|
163
167
|
|
|
168
|
+
// 0.5.0 registered the plain hourly task on every non-elevated Windows
|
|
169
|
+
// install and only mentioned it once, in the `init` summary. A later `doctor`
|
|
170
|
+
// has to name the loss (no catch-up after sleep, no logon pass, no retry) or
|
|
171
|
+
// the only symptom is silently missing hours.
|
|
172
|
+
function buildScheduleCheck(schedule = {}) {
|
|
173
|
+
const label = schedule.label || "Scheduled sync";
|
|
174
|
+
const meta = {
|
|
175
|
+
platform: schedule.platform || null,
|
|
176
|
+
label: schedule.label || null,
|
|
177
|
+
state: schedule.state || null,
|
|
178
|
+
enhanced: schedule.enhanced ?? null,
|
|
179
|
+
};
|
|
180
|
+
if (schedule.state === "unsupported") {
|
|
181
|
+
return {
|
|
182
|
+
id: "schedule.registered",
|
|
183
|
+
status: "ok",
|
|
184
|
+
critical: false,
|
|
185
|
+
detail: `${label}: unsupported platform (the pause flag covers manual runs)`,
|
|
186
|
+
meta,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
if (schedule.state === "missing") {
|
|
190
|
+
const why = schedule.detail ? ` — ${schedule.detail}` : "";
|
|
191
|
+
return {
|
|
192
|
+
id: "schedule.registered",
|
|
193
|
+
status: "warn",
|
|
194
|
+
critical: false,
|
|
195
|
+
detail: `${label} not registered${why}; run \`tokenusage init\` for hourly collection`,
|
|
196
|
+
meta,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
if (schedule.enhanced) {
|
|
200
|
+
return {
|
|
201
|
+
id: "schedule.registered",
|
|
202
|
+
status: "ok",
|
|
203
|
+
critical: false,
|
|
204
|
+
detail: `${label}: ${schedule.detail || "registered"}`,
|
|
205
|
+
meta,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
id: "schedule.registered",
|
|
210
|
+
status: "warn",
|
|
211
|
+
critical: false,
|
|
212
|
+
detail:
|
|
213
|
+
`${label} is ${schedule.detail || "a reduced definition"}; ` +
|
|
214
|
+
"re-run `tokenusage init` to restore catch-up/retry (0.5.1 and later register the full definition)",
|
|
215
|
+
meta: { ...meta, missing: schedule.missing || [] },
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
164
219
|
async function checkTrackerDir(trackerDir) {
|
|
165
220
|
try {
|
|
166
221
|
const st = await fs.stat(trackerDir);
|
|
@@ -227,6 +227,24 @@ function formatTaskStartBoundary(now = new Date()) {
|
|
|
227
227
|
return `${next.getFullYear()}-${pad(next.getMonth() + 1)}-${pad(next.getDate())}T${pad(next.getHours())}:00:00`;
|
|
228
228
|
}
|
|
229
229
|
|
|
230
|
+
/**
|
|
231
|
+
* The user a logon trigger fires for. `schtasks` resolves a `<LogonTrigger>`
|
|
232
|
+
* without `<UserId>` to "any user" and then refuses the definition with
|
|
233
|
+
* "Access is denied" unless the caller is elevated — which turned the whole
|
|
234
|
+
* definition into a plain hourly task on a normal install (2026-11-06,
|
|
235
|
+
* DESKTOP-MHFON1J). Naming the current user keeps the catch-up/retry
|
|
236
|
+
* definition registrable without admin.
|
|
237
|
+
*/
|
|
238
|
+
function windowsUserId({ env = process.env } = {}) {
|
|
239
|
+
if (env.USERDOMAIN && env.USERNAME) return `${env.USERDOMAIN}\\${env.USERNAME}`;
|
|
240
|
+
try {
|
|
241
|
+
const name = os.userInfo().username;
|
|
242
|
+
return name ? `${os.hostname()}\\${name}` : "";
|
|
243
|
+
} catch {
|
|
244
|
+
return "";
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
230
248
|
/**
|
|
231
249
|
* Task definition registered with `schtasks /Create /XML`. Compared to the
|
|
232
250
|
* plain `-SC HOURLY` registration this adds:
|
|
@@ -237,7 +255,7 @@ function formatTaskStartBoundary(now = new Date()) {
|
|
|
237
255
|
* MultipleInstancesPolicy=IgnoreNew keeps a second pass from racing the first
|
|
238
256
|
* (the CLI also holds sync.lock; this is the outer guard).
|
|
239
257
|
*/
|
|
240
|
-
function buildWindowsTaskXml({ vbsPath, startBoundary = formatTaskStartBoundary() }) {
|
|
258
|
+
function buildWindowsTaskXml({ vbsPath, startBoundary = formatTaskStartBoundary(), userId, logonTrigger = true }) {
|
|
241
259
|
// Element order mirrors what `schtasks /Query /XML` exports, so the
|
|
242
260
|
// definition passes the scheduler's validation on every Windows build.
|
|
243
261
|
return [
|
|
@@ -260,9 +278,14 @@ function buildWindowsTaskXml({ vbsPath, startBoundary = formatTaskStartBoundary(
|
|
|
260
278
|
" <DaysInterval>1</DaysInterval>",
|
|
261
279
|
" </ScheduleByDay>",
|
|
262
280
|
" </CalendarTrigger>",
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
281
|
+
...(logonTrigger
|
|
282
|
+
? [
|
|
283
|
+
" <LogonTrigger>",
|
|
284
|
+
...(userId ? [` <UserId>${xmlEscape(userId)}</UserId>`] : []),
|
|
285
|
+
" <Enabled>true</Enabled>",
|
|
286
|
+
" </LogonTrigger>",
|
|
287
|
+
]
|
|
288
|
+
: []),
|
|
266
289
|
" </Triggers>",
|
|
267
290
|
" <Principals>",
|
|
268
291
|
' <Principal id="Author">',
|
|
@@ -377,8 +400,12 @@ function buildSystemdTimer({ intervalSeconds = SCHEDULE_INTERVAL_SECONDS } = {})
|
|
|
377
400
|
].join("\n");
|
|
378
401
|
}
|
|
379
402
|
|
|
403
|
+
function runCapture(command, args) {
|
|
404
|
+
return execFileSync(command, args, { stdio: "pipe", windowsHide: true });
|
|
405
|
+
}
|
|
406
|
+
|
|
380
407
|
function run(command, args) {
|
|
381
|
-
|
|
408
|
+
runCapture(command, args);
|
|
382
409
|
}
|
|
383
410
|
|
|
384
411
|
// `stdio: "pipe"` keeps the child's own output on `error.stderr` / `stdout`,
|
|
@@ -484,35 +511,54 @@ function registerAutoSyncSchedule({
|
|
|
484
511
|
return { registered: false, platform: kind, label, reason: "unsupported_platform" };
|
|
485
512
|
}
|
|
486
513
|
|
|
487
|
-
function registerWindowsScheduledTask({ binDir, cliJs = cliEntryPath(), nodeExe = process.execPath, fallbackCliJs, now = new Date() }) {
|
|
514
|
+
function registerWindowsScheduledTask({ binDir, cliJs = cliEntryPath(), nodeExe = process.execPath, fallbackCliJs, now = new Date(), userId = windowsUserId() }) {
|
|
488
515
|
if (!isWindows()) return { registered: false, reason: "not_windows" };
|
|
489
516
|
try {
|
|
490
517
|
const vbsPath = writeHiddenRunner({ binDir, nodeExe, cliJs, fallbackCliJs });
|
|
491
518
|
const xmlPath = taskXmlPathFor(binDir);
|
|
492
|
-
const
|
|
519
|
+
const startBoundary = formatTaskStartBoundary(now);
|
|
493
520
|
// schtasks only accepts a Unicode (UTF-16) definition file.
|
|
494
|
-
|
|
495
|
-
|
|
521
|
+
const createFromXml = (options) => {
|
|
522
|
+
const xml = buildWindowsTaskXml({ vbsPath, startBoundary, ...options });
|
|
523
|
+
fs.writeFileSync(xmlPath, `\uFEFF${xml}`, { encoding: "utf16le", mode: 0o600 });
|
|
496
524
|
run("schtasks", ["/Create", "/F", "/TN", TASK_NAME, "/XML", xmlPath]);
|
|
525
|
+
};
|
|
526
|
+
try {
|
|
527
|
+
createFromXml({ userId });
|
|
497
528
|
return { registered: true, vbsPath, xmlPath };
|
|
498
|
-
} catch (
|
|
499
|
-
//
|
|
500
|
-
//
|
|
501
|
-
//
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
529
|
+
} catch (logonError) {
|
|
530
|
+
// A policy or older build can still refuse the logon trigger outright.
|
|
531
|
+
// Retry with the hourly definition alone: catch-up and retry survive,
|
|
532
|
+
// only the logon pass is gone — better than the plain hourly task.
|
|
533
|
+
try {
|
|
534
|
+
createFromXml({ userId, logonTrigger: false });
|
|
535
|
+
return {
|
|
536
|
+
registered: true,
|
|
537
|
+
degraded: true,
|
|
538
|
+
reason: "logon_trigger_rejected",
|
|
539
|
+
detail: errorText(logonError),
|
|
540
|
+
vbsPath,
|
|
541
|
+
xmlPath,
|
|
542
|
+
};
|
|
543
|
+
} catch (xmlError) {
|
|
544
|
+
// Locked-down policies and older builds can reject a custom definition;
|
|
545
|
+
// fall back to the plain hourly trigger (loses catch-up/retry but still
|
|
546
|
+
// collects), and say so instead of reporting a clean install.
|
|
547
|
+
run("schtasks", [
|
|
548
|
+
"/Create", "/F",
|
|
549
|
+
"/SC", "HOURLY", "/MO", "1",
|
|
550
|
+
"/TN", TASK_NAME,
|
|
551
|
+
"/TR", `wscript.exe "${vbsPath}"`,
|
|
552
|
+
]);
|
|
553
|
+
return {
|
|
554
|
+
registered: true,
|
|
555
|
+
degraded: true,
|
|
556
|
+
reason: "xml_rejected",
|
|
557
|
+
detail: errorText(xmlError),
|
|
558
|
+
vbsPath,
|
|
559
|
+
xmlPath,
|
|
560
|
+
};
|
|
561
|
+
}
|
|
516
562
|
}
|
|
517
563
|
} catch (error) {
|
|
518
564
|
return { registered: false, reason: errorText(error) };
|
|
@@ -587,6 +633,88 @@ function scheduleState({ home = os.homedir(), platform = process.platform } = {}
|
|
|
587
633
|
return "unknown";
|
|
588
634
|
}
|
|
589
635
|
|
|
636
|
+
/**
|
|
637
|
+
* What the *registered* schedule actually does. `init` prints the summary once,
|
|
638
|
+
* but a downgraded definition only shows up later as a missed catch-up after
|
|
639
|
+
* sleep — 0.5.0 silently fell back to the plain hourly task on every
|
|
640
|
+
* non-elevated Windows install, and `doctor` had no way to say so. Read the
|
|
641
|
+
* live definition (not the on-disk copy, which a later `init` may have
|
|
642
|
+
* rewritten) and report the reduced feature set.
|
|
643
|
+
*/
|
|
644
|
+
function inspectAutoSyncSchedule({
|
|
645
|
+
home = os.homedir(),
|
|
646
|
+
platform = process.platform,
|
|
647
|
+
exec = runCapture,
|
|
648
|
+
exists = fs.existsSync,
|
|
649
|
+
readFile = (file) => fs.readFileSync(file, "utf8"),
|
|
650
|
+
} = {}) {
|
|
651
|
+
const kind = schedulePlatform(platform);
|
|
652
|
+
const label = scheduleLabel(platform);
|
|
653
|
+
if (kind === "windows") {
|
|
654
|
+
let xml;
|
|
655
|
+
try {
|
|
656
|
+
xml = decodeStream(exec("schtasks", ["/Query", "/TN", TASK_NAME, "/XML"]));
|
|
657
|
+
} catch (error) {
|
|
658
|
+
return { platform: kind, label, state: "missing", detail: errorText(error) };
|
|
659
|
+
}
|
|
660
|
+
const features = {
|
|
661
|
+
catchUp: /<StartWhenAvailable>\s*true\s*</i.test(xml),
|
|
662
|
+
logon: /<LogonTrigger>/.test(xml),
|
|
663
|
+
retry: /<RestartOnFailure>/.test(xml),
|
|
664
|
+
unlimited: /<ExecutionTimeLimit>\s*PT0S\s*</i.test(xml),
|
|
665
|
+
};
|
|
666
|
+
const missing = [];
|
|
667
|
+
if (!features.catchUp) missing.push("catch-up");
|
|
668
|
+
if (!features.logon) missing.push("logon trigger");
|
|
669
|
+
if (!features.retry) missing.push("retry");
|
|
670
|
+
if (!features.unlimited) missing.push("unlimited runtime");
|
|
671
|
+
return {
|
|
672
|
+
platform: kind,
|
|
673
|
+
label,
|
|
674
|
+
state: "registered",
|
|
675
|
+
enhanced: missing.length === 0,
|
|
676
|
+
missing,
|
|
677
|
+
detail: missing.length
|
|
678
|
+
? `reduced definition (no ${missing.join(", ")})`
|
|
679
|
+
: "enhanced definition (catch-up, logon, retry)",
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
if (kind === "macos") {
|
|
683
|
+
const plistPath = launchAgentPath(home);
|
|
684
|
+
if (!exists(plistPath)) return { platform: kind, label, state: "missing", path: plistPath };
|
|
685
|
+
return {
|
|
686
|
+
platform: kind,
|
|
687
|
+
label,
|
|
688
|
+
state: "registered",
|
|
689
|
+
enhanced: true,
|
|
690
|
+
missing: [],
|
|
691
|
+
path: plistPath,
|
|
692
|
+
detail: "launchd agent installed",
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
if (kind === "linux") {
|
|
696
|
+
const timerPath = systemdTimerPath(home);
|
|
697
|
+
if (!exists(timerPath)) return { platform: kind, label, state: "missing", path: timerPath };
|
|
698
|
+
let timer = "";
|
|
699
|
+
try {
|
|
700
|
+
timer = readFile(timerPath);
|
|
701
|
+
} catch {
|
|
702
|
+
/* unreadable is reported below as the reduced state */
|
|
703
|
+
}
|
|
704
|
+
const persistent = /Persistent\s*=\s*true/i.test(timer);
|
|
705
|
+
return {
|
|
706
|
+
platform: kind,
|
|
707
|
+
label,
|
|
708
|
+
state: "registered",
|
|
709
|
+
enhanced: persistent,
|
|
710
|
+
missing: persistent ? [] : ["persistent timer"],
|
|
711
|
+
path: timerPath,
|
|
712
|
+
detail: persistent ? "user timer (Persistent=true)" : "user timer (no Persistent=true)",
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
return { platform: kind, label, state: "unsupported" };
|
|
716
|
+
}
|
|
717
|
+
|
|
590
718
|
/**
|
|
591
719
|
* Best-effort enable/disable of the registered schedule (pause/resume).
|
|
592
720
|
* "Not registered" is an expected, non-fatal state: the pause flag still
|
|
@@ -724,13 +852,21 @@ function scheduleDetailLine(value, max = 100) {
|
|
|
724
852
|
return clipLine(firstLine(value), max);
|
|
725
853
|
}
|
|
726
854
|
|
|
855
|
+
// What each degraded registration actually lost, so the summary names the
|
|
856
|
+
// real cost instead of one blanket "no catch-up/retry".
|
|
857
|
+
const DEGRADED_NOTES = {
|
|
858
|
+
xml_rejected: "no catch-up/retry settings",
|
|
859
|
+
logon_trigger_rejected: "catch-up/retry kept, no logon trigger",
|
|
860
|
+
};
|
|
861
|
+
|
|
727
862
|
function formatScheduleRegistration(outcome) {
|
|
728
863
|
if (!outcome) return "not registered";
|
|
729
864
|
if (outcome.registered) {
|
|
730
865
|
const when = "hourly, hidden window";
|
|
731
866
|
if (outcome.degraded) {
|
|
732
867
|
const why = scheduleDetailLine(outcome.detail);
|
|
733
|
-
|
|
868
|
+
const note = DEGRADED_NOTES[outcome.reason] || "reduced scheduling settings";
|
|
869
|
+
return `${outcome.label}: ${when} (degraded: ${outcome.reason}${why ? ` — ${why}` : ""}; ${note})`;
|
|
734
870
|
}
|
|
735
871
|
return `${outcome.label}: ${when} (pause/resume toggles it)`;
|
|
736
872
|
}
|
|
@@ -786,11 +922,13 @@ module.exports = {
|
|
|
786
922
|
buildSystemdService,
|
|
787
923
|
buildSystemdTimer,
|
|
788
924
|
formatTaskStartBoundary,
|
|
925
|
+
windowsUserId,
|
|
789
926
|
registerAutoSyncSchedule,
|
|
790
927
|
registerWindowsScheduledTask,
|
|
791
928
|
registerLaunchAgent,
|
|
792
929
|
registerSystemdTimer,
|
|
793
930
|
scheduleState,
|
|
931
|
+
inspectAutoSyncSchedule,
|
|
794
932
|
scheduleLabel,
|
|
795
933
|
setAutoSyncEnabled,
|
|
796
934
|
deleteAutoSyncSchedule,
|