tokenusage-cli 0.3.0 → 0.4.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +52 -11
  3. package/bin/tokenusage.js +14 -2
  4. package/package.json +1 -2
  5. package/src/cli.js +325 -78
  6. package/src/commands/device-login.js +3 -3
  7. package/src/commands/init.js +343 -153
  8. package/src/commands/pause.js +11 -23
  9. package/src/commands/reconcile.js +496 -0
  10. package/src/commands/sessions.js +57 -14
  11. package/src/commands/sync.js +69 -15
  12. package/src/commands/uninstall.js +6 -9
  13. package/src/commands/upload.js +147 -0
  14. package/src/lib/cli-errors.js +33 -0
  15. package/src/lib/cli-ui.js +93 -0
  16. package/src/lib/queue-row-normalize.js +55 -0
  17. package/src/lib/scheduled-task.js +597 -75
  18. package/src/lib/antigravity-paths.js +0 -48
  19. package/src/lib/async-queue-reader.js +0 -138
  20. package/src/lib/atomic-json.js +0 -27
  21. package/src/lib/bearer-token.js +0 -11
  22. package/src/lib/cloud-account.js +0 -541
  23. package/src/lib/codex-context-breakdown.js +0 -806
  24. package/src/lib/context-health.js +0 -124
  25. package/src/lib/grok-context-breakdown.js +0 -890
  26. package/src/lib/heatmap-compact.js +0 -114
  27. package/src/lib/local-api.js +0 -3574
  28. package/src/lib/outcomes-engine.js +0 -253
  29. package/src/lib/pet-packages.js +0 -722
  30. package/src/lib/skill-usage.js +0 -267
  31. package/src/lib/skills-manager.js +0 -1591
  32. package/src/lib/source-metadata.js +0 -48
  33. package/src/lib/subscription-manager.js +0 -293
  34. package/src/lib/wrapped-aggregator.js +0 -236
  35. package/test/audit-fixes.test.js +0 -249
  36. package/test/branding.test.js +0 -24
  37. package/test/cli-options.test.js +0 -43
  38. package/test/cli-smoke.test.js +0 -53
  39. package/test/cli-ui.test.js +0 -47
  40. package/test/collection-controls.test.js +0 -255
  41. package/test/ingest-sanitize.test.js +0 -162
  42. package/test/packaging.test.js +0 -107
  43. package/test/quiet-warnings.test.js +0 -53
  44. package/test/runtime-copy.test.js +0 -111
  45. package/test/session-upload.test.js +0 -427
  46. package/test/trae-db.test.js +0 -67
  47. package/test/zstd-native.test.js +0 -36
@@ -1,48 +1,115 @@
1
1
  "use strict";
2
2
 
3
- // Windows Task Scheduler registration for the hourly auto sync (0.2.0).
3
+ // Auto-sync schedule registration. init "takes over" the schedule that the
4
+ // 0.1.0 runbook left to a manual cron entry; three platforms, one contract:
4
5
  //
5
- // init "takes over" the registration that 0.1.0 left to a manual runbook:
6
- // the task action launches a VBS wrapper (GUI subsystem — no conhost flash
7
- // on Interactive tasks), which runs `node <bin entry> sync` fully hidden and
8
- // propagates the exit code via WScript.Quit. The CLI logs to a rolling
9
- // <trackerDir>/logs/sync.log itself (autoLog sink), so the registration no
10
- // longer needs a `>>` redirect — which also removes the cmd /c quoting
11
- // pitfall from the manual setup. pause/resume toggle the task with
12
- // /DISABLE //ENABLE so the hourly trigger stops firing while paused; the
13
- // pause flag in collection-pause.js guards everything else (notify/retry/
14
- // watch) cross-platform.
6
+ // Windows Task Scheduler task "TokenUsageSync" → wscript + hidden VBS runner
7
+ // macOS LaunchAgent com.token-usage.sync → /bin/sh launcher script
8
+ // Linux systemd --user timer token-usage-sync → /bin/sh launcher script
15
9
  //
16
- // Everything here is best-effort: a missing schtasks or an access error must
17
- // never fail init/pause/resume — the pause flag alone already stops syncs.
10
+ // The schedule only decides *when* sync runs. Every generated action runs
11
+ // `sync --from-scheduled`, which reports trigger=scheduled, self-logs into
12
+ // <trackerDir>/logs/sync.log and uploads without consulting the cloud-sync
13
+ // preference (the registered schedule is the default collection path, not an
14
+ // opt-in flavor). pause/resume toggle the schedule AND write the pause flag;
15
+ // the flag is the source of truth, so a machine whose schedule could not be
16
+ // registered still behaves.
17
+ //
18
+ // Windows specifics: the action launches the VBS wrapper (GUI subsystem → no
19
+ // conhost flash), which runs node fully hidden and propagates the exit code.
20
+ // The task definition is registered from XML (not `-SC HOURLY`) so it can carry
21
+ // StartWhenAvailable (catch up after a missed hour), a logon trigger (a reboot
22
+ // resumes collection immediately) and RestartOnFailure (retry a crashed pass)
23
+ // — those three are the reason the upstream CLI shelled out to PowerShell.
24
+ //
25
+ // Everything here is best-effort: a missing schtasks/launchctl/systemctl or an
26
+ // access error must never fail init/pause/resume/uninstall.
18
27
 
19
28
  const { execFileSync } = require("node:child_process");
20
29
  const fs = require("node:fs");
30
+ const os = require("node:os");
21
31
  const path = require("node:path");
22
32
 
23
33
  const TASK_NAME = "TokenUsageSync";
24
34
  const VBS_FILE = "run-sync-hidden.vbs";
35
+ const LAUNCHER_FILE = "run-sync-scheduled.sh";
36
+ const TASK_XML_FILE = "TokenUsageSync.xml";
37
+ const LAUNCH_AGENT_LABEL = "com.token-usage.sync";
38
+ const SYSTEMD_SERVICE_UNIT = "token-usage-sync.service";
39
+ const SYSTEMD_TIMER_UNIT = "token-usage-sync.timer";
40
+ const SCHEDULE_INTERVAL_SECONDS = 3600;
25
41
 
26
42
  function isWindows() {
27
43
  return process.platform === "win32";
28
44
  }
29
45
 
46
+ // "windows" | "macos" | "linux" | "unknown" — the single platform switch every
47
+ // dispatcher below reads, and the only thing tests have to override.
48
+ function schedulePlatform(platform = process.platform) {
49
+ if (platform === "win32") return "windows";
50
+ if (platform === "darwin") return "macos";
51
+ if (platform === "linux") return "linux";
52
+ return "unknown";
53
+ }
54
+
30
55
  function vbsPathFor(binDir) {
31
56
  return path.join(binDir, VBS_FILE);
32
57
  }
33
58
 
34
- // The task must launch the package's CLI entry, not src/cli.js: the latter is
35
- // a library that only exports run(), so a hidden `node src/cli.js sync ...`
36
- // exits 0 having collected nothing (the task then looks successful forever).
59
+ function launcherPathFor(binDir) {
60
+ return path.join(binDir, LAUNCHER_FILE);
61
+ }
62
+
63
+ function taskXmlPathFor(binDir) {
64
+ return path.join(binDir, TASK_XML_FILE);
65
+ }
66
+
67
+ function launchAgentPath(home = os.homedir()) {
68
+ return path.join(home, "Library", "LaunchAgents", `${LAUNCH_AGENT_LABEL}.plist`);
69
+ }
70
+
71
+ function systemdUserDir(home = os.homedir()) {
72
+ return path.join(home, ".config", "systemd", "user");
73
+ }
74
+
75
+ function systemdServicePath(home = os.homedir()) {
76
+ return path.join(systemdUserDir(home), SYSTEMD_SERVICE_UNIT);
77
+ }
78
+
79
+ function systemdTimerPath(home = os.homedir()) {
80
+ return path.join(systemdUserDir(home), SYSTEMD_TIMER_UNIT);
81
+ }
82
+
83
+ function scheduleLogDir(home = os.homedir()) {
84
+ return path.join(home, ".tokenusage", "tracker", "logs");
85
+ }
86
+
87
+ // Label a user sees in the platform's own control panel / unit list.
88
+ function scheduleLabel(platform = process.platform) {
89
+ switch (schedulePlatform(platform)) {
90
+ case "windows":
91
+ return TASK_NAME;
92
+ case "macos":
93
+ return LAUNCH_AGENT_LABEL;
94
+ case "linux":
95
+ return SYSTEMD_TIMER_UNIT;
96
+ default:
97
+ return TASK_NAME;
98
+ }
99
+ }
100
+
101
+ // The schedule must launch the package's CLI entry, not src/cli.js: the latter
102
+ // is a library that only exports run(), so a hidden `node src/cli.js sync ...`
103
+ // exits 0 having collected nothing (the schedule then looks successful forever).
37
104
  function cliEntryPath() {
38
105
  return path.resolve(__dirname, "..", "..", "bin", "tokenusage.js");
39
106
  }
40
107
 
41
108
  /**
42
- * The hidden-runner wrapper. Paths are quoted individually (via Chr(34), so
43
- * the VBS has no quote-escaping puzzles) and cmd is NOT involved: wscript
44
- * runs node directly, so the cmd /c outer-quote-stripping pitfall (paths with
45
- * spaces) never applies.
109
+ * The Windows hidden-runner wrapper. Paths are quoted individually (via
110
+ * Chr(34), so the VBS has no quote-escaping puzzles) and cmd is NOT involved:
111
+ * wscript runs node directly, so the cmd /c outer-quote-stripping pitfall
112
+ * (paths with spaces) never applies.
46
113
  *
47
114
  * `fallbackCliJs` is the init-copied runtime (trackerDir/app/bin/tracker.js).
48
115
  * The primary path lives in npm's global prefix, which nvm-windows makes
@@ -52,8 +119,7 @@ function cliEntryPath() {
52
119
  */
53
120
  function buildHiddenRunnerVbs({ nodeExe, cliJs, fallbackCliJs }) {
54
121
  // --from-scheduled: the run reports trigger=scheduled, self-logs via autoLog
55
- // and uploads without consulting the cloud-sync preference — the registered
56
- // task is the default collection path, not an opt-in flavor.
122
+ // and uploads without consulting the cloud-sync preference.
57
123
  const lines = [
58
124
  "' Token Usage — hidden sync runner.",
59
125
  "' The scheduled task launches this script (GUI subsystem: no conhost",
@@ -96,95 +162,551 @@ function writeHiddenRunner({
96
162
  return vbsPath;
97
163
  }
98
164
 
165
+ function xmlEscape(value) {
166
+ return String(value)
167
+ .replace(/&/g, "&amp;")
168
+ .replace(/</g, "&lt;")
169
+ .replace(/>/g, "&gt;")
170
+ .replace(/"/g, "&quot;");
171
+ }
172
+
173
+ function shSingleQuote(value) {
174
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
175
+ }
176
+
99
177
  /**
100
- * Register (idempotently — /F overwrites) the hourly hidden task. Returns
101
- * {registered: true} or {registered: false, reason} instead of throwing.
178
+ * POSIX launcher shared by macOS (launchd) and Linux (systemd --user). Keeping
179
+ * the fallback logic inside a script file — instead of inline in ProgramArguments
180
+ * or ExecStart — avoids two different quoting grammars (launchd XML vs systemd
181
+ * unit parsing) for the same paths.
102
182
  */
103
- function registerWindowsScheduledTask({
183
+ function buildSyncLauncherScript({ nodeExe = process.execPath, cliJs = cliEntryPath(), fallbackCliJs }) {
184
+ const lines = [
185
+ "#!/bin/sh",
186
+ "# Token Usage — scheduled sync launcher (generated by `tokenusage init`).",
187
+ "# Edited by hand? Re-run `tokenusage init` instead: it rewrites this file.",
188
+ `NODE=${shSingleQuote(nodeExe)}`,
189
+ `CLI=${shSingleQuote(cliJs)}`,
190
+ ];
191
+ if (fallbackCliJs) {
192
+ // nvm / homebrew upgrades move or drop the package path; the init-copied
193
+ // runtime under the data dir keeps collecting instead of failing silently.
194
+ lines.push(
195
+ `if [ ! -f "$CLI" ]; then CLI=${shSingleQuote(fallbackCliJs)}; fi`,
196
+ );
197
+ }
198
+ lines.push('exec "$NODE" "$CLI" sync --from-scheduled', "");
199
+ return lines.join("\n");
200
+ }
201
+
202
+ function writeSyncLauncher({ binDir, nodeExe, cliJs = cliEntryPath(), fallbackCliJs }) {
203
+ fs.mkdirSync(binDir, { recursive: true });
204
+ const launcherPath = launcherPathFor(binDir);
205
+ fs.writeFileSync(
206
+ launcherPath,
207
+ buildSyncLauncherScript({ nodeExe, cliJs, fallbackCliJs }),
208
+ { mode: 0o700 },
209
+ );
210
+ return launcherPath;
211
+ }
212
+
213
+ // Task Scheduler start boundary: local time, top of the next hour. A past
214
+ // boundary with a 1-hour repetition makes the scheduler fire immediately-ish
215
+ // and then hourly; a future one would delay the first pass by up to an hour.
216
+ function formatTaskStartBoundary(now = new Date()) {
217
+ const next = new Date(now.getTime());
218
+ next.setMinutes(0, 0, 0);
219
+ next.setHours(next.getHours() + 1);
220
+ const pad = (n) => String(n).padStart(2, "0");
221
+ return `${next.getFullYear()}-${pad(next.getMonth() + 1)}-${pad(next.getDate())}T${pad(next.getHours())}:00:00`;
222
+ }
223
+
224
+ /**
225
+ * Task definition registered with `schtasks /Create /XML`. Compared to the
226
+ * plain `-SC HOURLY` registration this adds:
227
+ * StartWhenAvailable — a missed hour (machine asleep) runs as soon as it can
228
+ * LogonTrigger — a reboot/logon resumes collection without waiting an hour
229
+ * RestartOnFailure — a crashed/erroring pass is retried up to 3 times
230
+ * ExecutionTimeLimit 0 — a long backlog drain is never killed mid-upload
231
+ * MultipleInstancesPolicy=IgnoreNew keeps a second pass from racing the first
232
+ * (the CLI also holds sync.lock; this is the outer guard).
233
+ */
234
+ function buildWindowsTaskXml({ vbsPath, startBoundary = formatTaskStartBoundary() }) {
235
+ // Element order mirrors what `schtasks /Query /XML` exports, so the
236
+ // definition passes the scheduler's validation on every Windows build.
237
+ return [
238
+ '<?xml version="1.0" encoding="UTF-16"?>',
239
+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
240
+ " <RegistrationInfo>",
241
+ ` <URI>\\${TASK_NAME}</URI>`,
242
+ " <Author>Token Usage</Author>",
243
+ " <Description>Hourly Token Usage sync (hidden). Registered by `tokenusage init`.</Description>",
244
+ " </RegistrationInfo>",
245
+ " <Triggers>",
246
+ " <CalendarTrigger>",
247
+ " <Repetition>",
248
+ " <Interval>PT1H</Interval>",
249
+ " <StopAtDurationEnd>false</StopAtDurationEnd>",
250
+ " </Repetition>",
251
+ ` <StartBoundary>${startBoundary}</StartBoundary>`,
252
+ " <Enabled>true</Enabled>",
253
+ " <ScheduleByDay>",
254
+ " <DaysInterval>1</DaysInterval>",
255
+ " </ScheduleByDay>",
256
+ " </CalendarTrigger>",
257
+ " <LogonTrigger>",
258
+ " <Enabled>true</Enabled>",
259
+ " </LogonTrigger>",
260
+ " </Triggers>",
261
+ " <Principals>",
262
+ ' <Principal id="Author">',
263
+ " <LogonType>InteractiveToken</LogonType>",
264
+ " <RunLevel>LeastPrivilege</RunLevel>",
265
+ " </Principal>",
266
+ " </Principals>",
267
+ " <Settings>",
268
+ " <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>",
269
+ " <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>",
270
+ " <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>",
271
+ " <AllowHardTerminate>true</AllowHardTerminate>",
272
+ " <StartWhenAvailable>true</StartWhenAvailable>",
273
+ " <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>",
274
+ " <IdleSettings>",
275
+ " <StopOnIdleEnd>false</StopOnIdleEnd>",
276
+ " <RestartOnIdle>false</RestartOnIdle>",
277
+ " </IdleSettings>",
278
+ " <AllowStartOnDemand>true</AllowStartOnDemand>",
279
+ " <Enabled>true</Enabled>",
280
+ " <Hidden>false</Hidden>",
281
+ " <RunOnlyIfIdle>false</RunOnlyIfIdle>",
282
+ " <WakeToRun>false</WakeToRun>",
283
+ " <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>",
284
+ " <Priority>7</Priority>",
285
+ " <RestartOnFailure>",
286
+ " <Interval>PT5M</Interval>",
287
+ " <Count>3</Count>",
288
+ " </RestartOnFailure>",
289
+ " </Settings>",
290
+ ' <Actions Context="Author">',
291
+ " <Exec>",
292
+ " <Command>wscript.exe</Command>",
293
+ ` <Arguments>"${xmlEscape(vbsPath)}"</Arguments>`,
294
+ " </Exec>",
295
+ " </Actions>",
296
+ "</Task>",
297
+ "",
298
+ ].join("\n");
299
+ }
300
+
301
+ function buildLaunchAgentPlist({
302
+ launcherPath,
303
+ logDir = scheduleLogDir(),
304
+ label = LAUNCH_AGENT_LABEL,
305
+ intervalSeconds = SCHEDULE_INTERVAL_SECONDS,
306
+ }) {
307
+ return [
308
+ '<?xml version="1.0" encoding="UTF-8"?>',
309
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
310
+ '<plist version="1.0">',
311
+ "<dict>",
312
+ " <key>Label</key>",
313
+ ` <string>${xmlEscape(label)}</string>`,
314
+ " <key>ProgramArguments</key>",
315
+ " <array>",
316
+ " <string>/bin/sh</string>",
317
+ ` <string>${xmlEscape(launcherPath)}</string>`,
318
+ " </array>",
319
+ " <key>StartInterval</key>",
320
+ ` <integer>${intervalSeconds}</integer>`,
321
+ " <key>RunAtLoad</key>",
322
+ " <true/>",
323
+ " <key>ProcessType</key>",
324
+ " <string>Background</string>",
325
+ " <key>StandardOutPath</key>",
326
+ ` <string>${xmlEscape(path.join(logDir, "scheduled.out.log"))}</string>`,
327
+ " <key>StandardErrorPath</key>",
328
+ ` <string>${xmlEscape(path.join(logDir, "scheduled.err.log"))}</string>`,
329
+ "</dict>",
330
+ "</plist>",
331
+ "",
332
+ ].join("\n");
333
+ }
334
+
335
+ // systemd treats `%` as a specifier, so a path containing one must be doubled
336
+ // inside a unit file.
337
+ function systemdLiteral(value) {
338
+ return String(value).replace(/%/g, "%%");
339
+ }
340
+
341
+ function buildSystemdService({ launcherPath }) {
342
+ return [
343
+ "[Unit]",
344
+ "Description=Token Usage hourly sync",
345
+ "Wants=network-online.target",
346
+ "After=network-online.target",
347
+ "",
348
+ "[Service]",
349
+ "Type=oneshot",
350
+ `ExecStart=/bin/sh ${systemdLiteral(launcherPath)}`,
351
+ "Nice=10",
352
+ "",
353
+ ].join("\n");
354
+ }
355
+
356
+ function buildSystemdTimer({ intervalSeconds = SCHEDULE_INTERVAL_SECONDS } = {}) {
357
+ const minutes = Math.round(intervalSeconds / 60);
358
+ return [
359
+ "[Unit]",
360
+ "Description=Run the Token Usage sync hourly",
361
+ "",
362
+ "[Timer]",
363
+ `OnBootSec=${minutes}min`,
364
+ `OnUnitInactiveSec=${minutes}min`,
365
+ "Persistent=true",
366
+ "AccuracySec=1min",
367
+ "",
368
+ "[Install]",
369
+ "WantedBy=timers.target",
370
+ "",
371
+ ].join("\n");
372
+ }
373
+
374
+ function run(command, args) {
375
+ execFileSync(command, args, { stdio: "pipe", windowsHide: true });
376
+ }
377
+
378
+ function errorText(error) {
379
+ return String(error?.message || error).slice(0, 200);
380
+ }
381
+
382
+ /**
383
+ * Register (idempotently) the hourly hidden schedule. Returns
384
+ * {registered, platform, label, reason, degraded} instead of throwing.
385
+ */
386
+ function registerAutoSyncSchedule({
104
387
  binDir,
388
+ home = os.homedir(),
105
389
  cliJs = cliEntryPath(),
106
390
  nodeExe = process.execPath,
107
391
  fallbackCliJs,
108
- }) {
392
+ platform = process.platform,
393
+ now = new Date(),
394
+ } = {}) {
395
+ const kind = schedulePlatform(platform);
396
+ const label = scheduleLabel(platform);
397
+ if (kind === "windows") {
398
+ const outcome = registerWindowsScheduledTask({ binDir, cliJs, nodeExe, fallbackCliJs, now });
399
+ return { ...outcome, platform: kind, label };
400
+ }
401
+ if (kind === "macos") {
402
+ return registerLaunchAgent({ binDir, home, cliJs, nodeExe, fallbackCliJs });
403
+ }
404
+ if (kind === "linux") {
405
+ return registerSystemdTimer({ binDir, home, cliJs, nodeExe, fallbackCliJs });
406
+ }
407
+ return { registered: false, platform: kind, label, reason: "unsupported_platform" };
408
+ }
409
+
410
+ function registerWindowsScheduledTask({ binDir, cliJs = cliEntryPath(), nodeExe = process.execPath, fallbackCliJs, now = new Date() }) {
109
411
  if (!isWindows()) return { registered: false, reason: "not_windows" };
110
412
  try {
111
413
  const vbsPath = writeHiddenRunner({ binDir, nodeExe, cliJs, fallbackCliJs });
112
- execFileSync(
113
- "schtasks",
114
- [
414
+ const xmlPath = taskXmlPathFor(binDir);
415
+ const xml = buildWindowsTaskXml({ vbsPath, startBoundary: formatTaskStartBoundary(now) });
416
+ // schtasks only accepts a Unicode (UTF-16) definition file.
417
+ fs.writeFileSync(xmlPath, `\uFEFF${xml}`, { encoding: "utf16le", mode: 0o600 });
418
+ try {
419
+ run("schtasks", ["/Create", "/F", "/TN", TASK_NAME, "/XML", xmlPath]);
420
+ return { registered: true, vbsPath, xmlPath };
421
+ } catch (xmlError) {
422
+ // Locked-down policies and older builds can reject a custom definition;
423
+ // fall back to the plain hourly trigger (loses catch-up/retry but still
424
+ // collects), and say so instead of reporting a clean install.
425
+ run("schtasks", [
115
426
  "/Create", "/F",
116
427
  "/SC", "HOURLY", "/MO", "1",
117
428
  "/TN", TASK_NAME,
118
429
  "/TR", `wscript.exe "${vbsPath}"`,
119
- ],
120
- { stdio: "pipe", windowsHide: true },
121
- );
122
- return { registered: true, vbsPath };
430
+ ]);
431
+ return {
432
+ registered: true,
433
+ degraded: true,
434
+ reason: "xml_rejected",
435
+ detail: errorText(xmlError),
436
+ vbsPath,
437
+ xmlPath,
438
+ };
439
+ }
123
440
  } catch (error) {
124
- return { registered: false, reason: String(error?.message || error).slice(0, 200) };
441
+ return { registered: false, reason: errorText(error) };
125
442
  }
126
443
  }
127
444
 
128
- // Existence probe so pause/resume can report "no task" (expected on machines
129
- // that never registered it) distinctly from a real toggle failure. schtasks
130
- // output is localized; exit codes are not, so this uses /Query success only.
131
- function windowsTaskExists() {
132
- if (!isWindows()) return null;
445
+ function registerLaunchAgent({ binDir, home = os.homedir(), cliJs = cliEntryPath(), nodeExe = process.execPath, fallbackCliJs }) {
133
446
  try {
134
- execFileSync("schtasks", ["/Query", "/TN", TASK_NAME], {
135
- stdio: "pipe",
136
- windowsHide: true,
137
- });
138
- return true;
139
- } catch {
140
- return false;
447
+ const launcherPath = writeSyncLauncher({ binDir, nodeExe, cliJs, fallbackCliJs });
448
+ const plistPath = launchAgentPath(home);
449
+ fs.mkdirSync(path.dirname(plistPath), { recursive: true });
450
+ const logDir = scheduleLogDir(home);
451
+ fs.mkdirSync(logDir, { recursive: true });
452
+ fs.writeFileSync(plistPath, buildLaunchAgentPlist({ launcherPath, logDir }), { mode: 0o644 });
453
+ const uid = typeof process.getuid === "function" ? process.getuid() : 501;
454
+ // bootout first: bootstrap fails when the label is already loaded, and a
455
+ // re-run of init must be able to overwrite its own agent.
456
+ try {
457
+ run("launchctl", ["bootout", `gui/${uid}/${LAUNCH_AGENT_LABEL}`]);
458
+ } catch {
459
+ /* not loaded yet — expected on a first install */
460
+ }
461
+ try {
462
+ run("launchctl", ["bootstrap", `gui/${uid}`, plistPath]);
463
+ } catch (error) {
464
+ // Older macOS releases have no bootstrap subcommand.
465
+ run("launchctl", ["load", "-w", plistPath]);
466
+ return { registered: true, launcherPath, plistPath, degraded: true, reason: "legacy_launchctl", detail: errorText(error) };
467
+ }
468
+ return { registered: true, launcherPath, plistPath };
469
+ } catch (error) {
470
+ return { registered: false, reason: errorText(error) };
141
471
  }
142
472
  }
143
473
 
144
- // Best-effort enable/disable of the hourly task (pause/resume). "Task
145
- // missing" is an expected, non-fatal state (uninstalled task, non-Windows,
146
- // never-registered installs) — the pause flag still guards every auto flavor.
147
- function setWindowsTaskEnabled(enabled) {
148
- if (!isWindows()) return { changed: false, reason: "not_windows" };
149
- if (windowsTaskExists() === false) {
150
- return { changed: false, reason: "task_missing" };
151
- }
474
+ function registerSystemdTimer({ binDir, home = os.homedir(), cliJs = cliEntryPath(), nodeExe = process.execPath, fallbackCliJs }) {
152
475
  try {
153
- execFileSync(
154
- "schtasks",
155
- ["/Change", "/TN", TASK_NAME, enabled ? "/ENABLE" : "/DISABLE"],
156
- { stdio: "pipe", windowsHide: true },
157
- );
158
- return { changed: true };
476
+ const launcherPath = writeSyncLauncher({ binDir, nodeExe, cliJs, fallbackCliJs });
477
+ const servicePath = systemdServicePath(home);
478
+ const timerPath = systemdTimerPath(home);
479
+ fs.mkdirSync(path.dirname(servicePath), { recursive: true });
480
+ fs.writeFileSync(servicePath, buildSystemdService({ launcherPath }), { mode: 0o644 });
481
+ fs.writeFileSync(timerPath, buildSystemdTimer(), { mode: 0o644 });
482
+ run("systemctl", ["--user", "daemon-reload"]);
483
+ run("systemctl", ["--user", "enable", "--now", SYSTEMD_TIMER_UNIT]);
484
+ return { registered: true, launcherPath, servicePath, timerPath };
159
485
  } catch (error) {
160
- return { changed: false, reason: "error", detail: String(error?.message || error).slice(0, 200) };
486
+ return { registered: false, reason: errorText(error) };
161
487
  }
162
488
  }
163
489
 
164
- // uninstall teardown: delete the task (best-effort, idempotent).
165
- function deleteWindowsScheduledTask() {
166
- if (!isWindows()) return { deleted: false, reason: "not_windows" };
167
- try {
168
- execFileSync("schtasks", ["/Delete", "/F", "/TN", TASK_NAME], {
169
- stdio: "pipe",
170
- windowsHide: true,
171
- });
172
- return { deleted: true };
173
- } catch (error) {
174
- return { deleted: false, reason: String(error?.message || error).slice(0, 200) };
490
+ // Existence probe so pause/resume can report "not registered" (expected on
491
+ // machines that never ran init with a schedule) distinctly from a real toggle
492
+ // failure. Files first (cheap, non-fatal); platform tools only confirm.
493
+ function scheduleState({ home = os.homedir(), platform = process.platform } = {}) {
494
+ const kind = schedulePlatform(platform);
495
+ if (kind === "windows") {
496
+ if (!isWindows()) return "unknown";
497
+ try {
498
+ run("schtasks", ["/Query", "/TN", TASK_NAME]);
499
+ return "registered";
500
+ } catch {
501
+ return "missing";
502
+ }
503
+ }
504
+ if (kind === "macos") {
505
+ return fs.existsSync(launchAgentPath(home)) ? "registered" : "missing";
175
506
  }
507
+ if (kind === "linux") {
508
+ return fs.existsSync(systemdTimerPath(home)) ? "registered" : "missing";
509
+ }
510
+ return "unknown";
511
+ }
512
+
513
+ /**
514
+ * Best-effort enable/disable of the registered schedule (pause/resume).
515
+ * "Not registered" is an expected, non-fatal state: the pause flag still
516
+ * guards every auto flavor.
517
+ */
518
+ function setAutoSyncEnabled(enabled, { home = os.homedir(), platform = process.platform } = {}) {
519
+ const kind = schedulePlatform(platform);
520
+ const label = scheduleLabel(platform);
521
+ if (kind === "windows") {
522
+ if (!isWindows()) return { changed: false, platform: kind, label, reason: "unsupported_platform" };
523
+ try {
524
+ run("schtasks", ["/Change", "/TN", TASK_NAME, enabled ? "/ENABLE" : "/DISABLE"]);
525
+ return { changed: true, platform: kind, label };
526
+ } catch (error) {
527
+ return { changed: false, platform: kind, label, reason: errorText(error) };
528
+ }
529
+ }
530
+ if (kind === "macos") {
531
+ const plistPath = launchAgentPath(home);
532
+ if (!fs.existsSync(plistPath)) {
533
+ return { changed: false, platform: kind, label, reason: "schedule_missing" };
534
+ }
535
+ const uid = typeof process.getuid === "function" ? process.getuid() : 501;
536
+ const domain = `gui/${uid}/${LAUNCH_AGENT_LABEL}`;
537
+ try {
538
+ if (enabled) run("launchctl", ["bootstrap", `gui/${uid}`, plistPath]);
539
+ else run("launchctl", ["bootout", domain]);
540
+ } catch (error) {
541
+ // Already loaded (resume) or already unloaded (pause) are both no-ops.
542
+ if (isBenignLaunchctlFailure(error)) {
543
+ return { changed: true, platform: kind, label };
544
+ }
545
+ return { changed: false, platform: kind, label, reason: errorText(error) };
546
+ }
547
+ return { changed: true, platform: kind, label };
548
+ }
549
+ if (kind === "linux") {
550
+ if (!fs.existsSync(systemdTimerPath(home))) {
551
+ return { changed: false, platform: kind, label, reason: "schedule_missing" };
552
+ }
553
+ try {
554
+ if (enabled) run("systemctl", ["--user", "enable", "--now", SYSTEMD_TIMER_UNIT]);
555
+ else run("systemctl", ["--user", "disable", "--now", SYSTEMD_TIMER_UNIT]);
556
+ return { changed: true, platform: kind, label };
557
+ } catch (error) {
558
+ return { changed: false, platform: kind, label, reason: errorText(error) };
559
+ }
560
+ }
561
+ return { changed: false, platform: kind, label, reason: "unsupported_platform" };
562
+ }
563
+
564
+ function isBenignLaunchctlFailure(error) {
565
+ const text = String(error?.stderr || error?.message || error);
566
+ // launchd says "already bootstrapped" / "service not found"; neither is a
567
+ // real failure for our purpose (resume when loaded, pause when absent).
568
+ return /already (bootstrapped|loaded)/i.test(text) ||
569
+ /service not found|no such (process|service)|not find service/i.test(text);
570
+ }
571
+
572
+ // uninstall teardown: delete the task/agent/timer and the generated runner
573
+ // files (best-effort, idempotent).
574
+ function deleteAutoSyncSchedule({ home = os.homedir(), binDir, platform = process.platform } = {}) {
575
+ const kind = schedulePlatform(platform);
576
+ const label = scheduleLabel(platform);
577
+ const removals = [];
578
+ if (binDir) {
579
+ for (const file of [VBS_FILE, LAUNCHER_FILE, TASK_XML_FILE]) {
580
+ try {
581
+ fs.unlinkSync(path.join(binDir, file));
582
+ removals.push(file);
583
+ } catch {
584
+ /* never installed on this platform */
585
+ }
586
+ }
587
+ }
588
+ if (kind === "windows") {
589
+ if (!isWindows()) return { deleted: false, platform: kind, label, reason: "unsupported_platform" };
590
+ try {
591
+ run("schtasks", ["/Delete", "/F", "/TN", TASK_NAME]);
592
+ return { deleted: true, platform: kind, label };
593
+ } catch (error) {
594
+ return { deleted: false, platform: kind, label, reason: errorText(error) };
595
+ }
596
+ }
597
+ if (kind === "macos") {
598
+ const plistPath = launchAgentPath(home);
599
+ const uid = typeof process.getuid === "function" ? process.getuid() : 501;
600
+ try {
601
+ run("launchctl", ["bootout", `gui/${uid}/${LAUNCH_AGENT_LABEL}`]);
602
+ } catch {
603
+ /* not loaded — still remove the file below */
604
+ }
605
+ try {
606
+ fs.unlinkSync(plistPath);
607
+ return { deleted: true, platform: kind, label };
608
+ } catch (error) {
609
+ return { deleted: false, platform: kind, label, reason: errorText(error) };
610
+ }
611
+ }
612
+ if (kind === "linux") {
613
+ try {
614
+ run("systemctl", ["--user", "disable", "--now", SYSTEMD_TIMER_UNIT]);
615
+ } catch {
616
+ /* unit not loaded or systemd unavailable — remove the files below */
617
+ }
618
+ let deleted = false;
619
+ for (const unitPath of [systemdServicePath(home), systemdTimerPath(home)]) {
620
+ try {
621
+ fs.unlinkSync(unitPath);
622
+ deleted = true;
623
+ } catch {
624
+ /* not installed */
625
+ }
626
+ }
627
+ try {
628
+ run("systemctl", ["--user", "daemon-reload"]);
629
+ } catch {
630
+ /* systemd unavailable */
631
+ }
632
+ return deleted
633
+ ? { deleted: true, platform: kind, label }
634
+ : { deleted: false, platform: kind, label, reason: "schedule_missing" };
635
+ }
636
+ return { deleted: false, platform: kind, label, reason: "unsupported_platform" };
637
+ }
638
+
639
+ // One place for the init summary copy so Windows/macOS/Linux cannot drift.
640
+ function formatScheduleRegistration(outcome) {
641
+ if (!outcome) return "not registered";
642
+ if (outcome.registered) {
643
+ const when = "hourly, hidden window";
644
+ if (outcome.degraded) {
645
+ return `${outcome.label}: ${when} (degraded: ${outcome.reason}; no catch-up/retry settings)`;
646
+ }
647
+ return `${outcome.label}: ${when} (pause/resume toggles it)`;
648
+ }
649
+ if (outcome.reason === "unsupported_platform") {
650
+ return "Unsupported platform; schedule `tokenusage sync` yourself (cron/launchd)";
651
+ }
652
+ return `Not registered: ${outcome.reason}`;
653
+ }
654
+
655
+ function formatScheduleToggle(outcome, enabled) {
656
+ const action = enabled ? "enabled" : "disabled";
657
+ if (outcome?.changed) return `${outcome.label} ${action}.`;
658
+ if (outcome?.reason === "unsupported_platform") {
659
+ return `(Scheduled sync: not supported on this platform — the pause flag covers manual/cron runs).`;
660
+ }
661
+ if (outcome?.reason === "schedule_missing") {
662
+ return `${outcome.label} not found (nothing to ${action}) — the pause flag still guards all auto syncs.`;
663
+ }
664
+ return `${outcome?.label || TASK_NAME} could not be ${action} (${outcome?.reason || "unknown error"}) — the pause flag still guards all auto syncs.`;
665
+ }
666
+
667
+ function formatScheduleDelete(outcome) {
668
+ if (outcome?.deleted) return `- Scheduled sync deleted: ${outcome.label}`;
669
+ if (outcome?.reason === "unsupported_platform") return "- Scheduled sync: none (unsupported platform)";
670
+ return "- Scheduled sync: none";
176
671
  }
177
672
 
178
673
  module.exports = {
179
674
  TASK_NAME,
180
675
  VBS_FILE,
676
+ LAUNCHER_FILE,
677
+ TASK_XML_FILE,
678
+ LAUNCH_AGENT_LABEL,
679
+ SYSTEMD_SERVICE_UNIT,
680
+ SYSTEMD_TIMER_UNIT,
681
+ SCHEDULE_INTERVAL_SECONDS,
181
682
  isWindows,
683
+ schedulePlatform,
182
684
  vbsPathFor,
685
+ launcherPathFor,
686
+ taskXmlPathFor,
687
+ launchAgentPath,
688
+ systemdUserDir,
689
+ systemdServicePath,
690
+ systemdTimerPath,
183
691
  cliEntryPath,
184
692
  buildHiddenRunnerVbs,
185
693
  writeHiddenRunner,
694
+ buildSyncLauncherScript,
695
+ writeSyncLauncher,
696
+ buildWindowsTaskXml,
697
+ buildLaunchAgentPlist,
698
+ buildSystemdService,
699
+ buildSystemdTimer,
700
+ formatTaskStartBoundary,
701
+ registerAutoSyncSchedule,
186
702
  registerWindowsScheduledTask,
187
- windowsTaskExists,
188
- setWindowsTaskEnabled,
189
- deleteWindowsScheduledTask,
703
+ registerLaunchAgent,
704
+ registerSystemdTimer,
705
+ scheduleState,
706
+ scheduleLabel,
707
+ setAutoSyncEnabled,
708
+ deleteAutoSyncSchedule,
709
+ formatScheduleRegistration,
710
+ formatScheduleToggle,
711
+ formatScheduleDelete,
190
712
  };