@ponbac/token-ledger 0.4.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.
Files changed (3) hide show
  1. package/README.md +41 -5
  2. package/dist/main.js +133 -63
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -493,6 +493,9 @@ Run it on **every machine** where you use a coding agent, and schedule it daily.
493
493
  machine ID and a label taken from the host name. Edit the label freely, but keep
494
494
  the ID: a new ID makes the same history count again as another machine.
495
495
 
496
+ A machine's first upload takes in all the history found on it, back to its earliest
497
+ usage, and says so. Every sync after that covers the last 14 days.
498
+
496
499
  If you map projects in a `token-ledger.json`, pass it with `--config`; scheduled jobs
497
500
  do not run in your project directory. Days follow the system time zone; add
498
501
  `--time-zone Europe/Stockholm` when a scheduler's environment may lack one.
@@ -521,6 +524,15 @@ does not keep a process running. Run it again to change the job.
521
524
  `journalctl --user -u token-ledger-sync` on Linux and in
522
525
  `~/Library/Logs/token-ledger-sync.log` on macOS.
523
526
 
527
+ On Windows, scheduled sync runs in the background without opening a terminal
528
+ window. A [Windows Script Host](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/wscript)
529
+ launcher in your token-ledger settings directory waits for sync to finish and
530
+ passes its exit code back to Task Scheduler. Windows Script Host must be enabled.
531
+ To update a task installed by an older CLI version, run
532
+ `npx.cmd --yes @ponbac/token-ledger@latest schedule install` again, including any
533
+ `--at`, `--config`, `--time-zone`, or `--provider` options you used before. This
534
+ replaces the existing task; your saved server and token are kept.
535
+
524
536
  | Platform | Scheduler | A missed run |
525
537
  | -------- | ------------------- | ------------------------------------------------------ |
526
538
  | Linux | systemd user timer | Runs within ten minutes of your next login |
@@ -629,13 +641,17 @@ but does not replay intervals missed while powered off.
629
641
  **Windows (Task Scheduler).** In PowerShell:
630
642
 
631
643
  ```powershell
632
- $action = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c npx --yes @ponbac/token-ledger@latest sync"
644
+ $runner = Join-Path $env:APPDATA "token-ledger\token-ledger-sync.js"
645
+ New-Item -ItemType Directory -Path (Split-Path $runner) -Force | Out-Null
646
+ 'WScript.Quit(WScript.CreateObject("WScript.Shell").Run("cmd.exe /d /v:off /c npx --yes @ponbac/token-ledger@latest sync", 0, true));' | Set-Content -Path $runner -Encoding ASCII
647
+ $action = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "//B //Nologo //E:JScript `"$runner`""
633
648
  $trigger = New-ScheduledTaskTrigger -Daily -At 12:30
634
649
  $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
635
- Register-ScheduledTask -TaskName "token-ledger sync" -Action $action -Trigger $trigger -Settings $settings
650
+ Register-ScheduledTask -TaskName "token-ledger sync" -Action $action -Trigger $trigger -Settings $settings -Force
636
651
  ```
637
652
 
638
- `-StartWhenAvailable` runs a missed sync at the next opportunity. The battery
653
+ The launcher hides the sync window and waits for its exit code. `//B` prevents
654
+ script dialogs. `-StartWhenAvailable` runs a missed sync at the next opportunity. The battery
639
655
  switches allow starts on battery and keep a running sync from being stopped when
640
656
  AC power disconnects. See [Task Scheduler settings](https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtasksettingsset).
641
657
 
@@ -661,7 +677,27 @@ See [the payload contract](docs/sync-v1.md) for every field.
661
677
 
662
678
  ### Windows and re-syncing
663
679
 
664
- The default window is the last 14 local days. For each provider whose history was
680
+ The default window is the last 14 local days, except for a machine's first upload,
681
+ which reaches back to the earliest usage found on it. Before scanning, and again just
682
+ before sending, `sync` asks the server whether it has stored anything from this
683
+ machine. Only when the server plainly answers that it has not is the whole history
684
+ sent: a long window then has nothing to replace. If the server already lists the
685
+ machine, the sync is an ordinary one, whatever the settings directory holds, so
686
+ restored settings or a lost reply do not lead to a second whole-history upload. If the
687
+ server cannot be asked, `sync` says so, sends the ordinary window, and leaves earlier
688
+ history to `--since`. Two machines sharing one `machine.json` replace each other's
689
+ usage on every sync, and a first upload is no exception.
690
+
691
+ Passing `--since` chooses the window yourself, on a first upload as on any other.
692
+ `sync --dry-run` asks the same question when it has a server and token, and shows the
693
+ payload a real run would send; without them it shows the ordinary window and says why.
694
+ If the server refuses a whole history as too large, `sync` uploads the last 14 days
695
+ instead and says how to send the rest in parts. The first upload is the machine's, not
696
+ each tool's: a tool left out of it with `--provider`, or whose history cannot be read
697
+ then, is not sent in full later by itself. `sync` says so at the time; send that
698
+ tool's earlier history afterwards with `--provider` and `--since`.
699
+
700
+ For each provider whose history was
665
701
  fully read, the server replaces what this machine previously sent for that provider
666
702
  in the window, so repeated syncs never double count, and machines add up. Fully read
667
703
  means every file that could hold usage in the window: older transcripts are
@@ -726,7 +762,7 @@ For manual publication:
726
762
  1. Log in with `npm login` using an account with publish access to `@ponbac/token-ledger`.
727
763
  2. Run `bun run check`. The CLI test packs the package, installs it offline outside
728
764
  the repository with lifecycle scripts disabled, and exercises the installed CLI.
729
- 3. Run `bun run pack` to create `dist/ponbac-token-ledger-0.4.0.tgz` (filename follows version).
765
+ 3. Run `bun run pack` to create `dist/ponbac-token-ledger-0.5.1.tgz` (filename follows version).
730
766
  4. Inspect `npm publish ./dist/npm --dry-run`.
731
767
  5. Publish with `npm publish ./dist/npm --access public`; complete npm's authentication
732
768
  prompt if requested.
package/dist/main.js CHANGED
@@ -35162,6 +35162,7 @@ function planHints() {
35162
35162
 
35163
35163
  // packages/core/src/ledger.ts
35164
35164
  var modifiedSlack = 36 * 60 * 60 * 1000;
35165
+ var historyFloor = Date.UTC(2020, 0, 1);
35165
35166
 
35166
35167
  class InvalidRequest extends exports_Schema.TaggedError()("InvalidRequest", {
35167
35168
  message: exports_Schema.String
@@ -35335,18 +35336,28 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35335
35336
  coverage
35336
35337
  });
35337
35338
  });
35338
- const syncPayload = exports_Effect.fn("Ledger.syncPayload")(function* (input, clientInput) {
35339
+ const payloadFrom = exports_Effect.fn("Ledger.payloadFrom")(function* (input, clientInput, history) {
35339
35340
  const request3 = yield* decode5(input);
35340
35341
  const client = yield* exports_Schema.decodeUnknownEffect(SyncClient)(clientInput).pipe(exports_Effect.mapError(() => new InvalidRequest({
35341
35342
  message: "Expected a machine UUID and label and a client version."
35342
35343
  })));
35343
- const window = hourRange(dayWindow(request3.since, request3.until, request3.timeZone));
35344
+ const requested = hourRange(dayWindow(request3.since, request3.until, request3.timeZone));
35345
+ const from = history ? Math.min(historyFloor, requested.start) : requested.start;
35344
35346
  const buckets = sessionBuckets(request3.pricing);
35345
35347
  const hints = planHints();
35346
- const coverage = yield* scan2(request3, window.start, (timestamp2) => timestamp2 >= window.start && timestamp2 < window.end ? timestamp2 : undefined, (record3, attribution) => buckets.add(record3, attribution.shareable ? attribution.project : unattributed), (plan) => hints.add(plan));
35348
+ let earliest = requested.start;
35349
+ const coverage = yield* scan2(request3, from, (timestamp2) => timestamp2 >= from && timestamp2 < requested.end ? timestamp2 : undefined, (record3, attribution, timestamp2) => {
35350
+ earliest = Math.min(earliest, timestamp2);
35351
+ buckets.add(record3, attribution.shareable ? attribution.project : unattributed);
35352
+ }, (plan) => {
35353
+ earliest = Math.min(earliest, plan.timestamp);
35354
+ hints.add(plan);
35355
+ });
35356
+ const since = earliest < requested.start ? exports_DateTime.formatIsoDate(exports_DateTime.setZone(exports_DateTime.makeUnsafe(earliest), request3.timeZone)) : request3.since;
35357
+ const window = since === request3.since ? requested : hourRange(dayWindow(since, request3.until, request3.timeZone));
35347
35358
  const summary = providerCoverage(coverage);
35348
35359
  const replaced = replacedProviders(summary);
35349
- return yield* SyncPayload.makeEffect({
35360
+ const payload = yield* SyncPayload.makeEffect({
35350
35361
  version: 1,
35351
35362
  machine: client.machine,
35352
35363
  clientVersion: client.version,
@@ -35368,8 +35379,13 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35368
35379
  }).pipe(exports_Effect.mapError(() => new InvalidRequest({
35369
35380
  message: "Report data must satisfy the sync payload contract."
35370
35381
  })));
35382
+ return { payload, since };
35383
+ });
35384
+ return Ledger.of({
35385
+ report,
35386
+ syncPayload: (request3, client) => exports_Effect.map(payloadFrom(request3, client, false), ({ payload }) => payload),
35387
+ historyPayload: (request3, client) => payloadFrom(request3, client, true)
35371
35388
  });
35372
- return Ledger.of({ report, syncPayload });
35373
35389
  }));
35374
35390
  }
35375
35391
  function acceptsFile(source, file2) {
@@ -42683,7 +42699,7 @@ var runWith2 = (command, config) => {
42683
42699
  // packages/cli/package.json
42684
42700
  var package_default = {
42685
42701
  name: "@ponbac/token-ledger",
42686
- version: "0.4.0",
42702
+ version: "0.5.1",
42687
42703
  private: true,
42688
42704
  type: "module",
42689
42705
  bin: {
@@ -43983,46 +43999,56 @@ var powershellArguments = (script) => [
43983
43999
  ...powershellOptions,
43984
44000
  Buffer.from(script, "utf16le").toString("base64")
43985
44001
  ];
43986
- var taskScheduler = {
43987
- name: "Task Scheduler task",
43988
- install: (job) => quotable(job, /[\p{Cc}"%]/u, 'a control character, `"`, or `%`').pipe(exports_Effect.map((job2) => {
43989
- const command = [
43990
- ...exports_Option.toArray(job2.configHome).map((directory) => `set "XDG_CONFIG_HOME=${directory}"`),
43991
- `set "PATH=${job2.nodeDirectory};%PATH%"`,
43992
- `npx --yes ${packageSpec} ${["sync", ...job2.flags].map(cmdWord).join(" ")}`
43993
- ].join(" && ");
43994
- const script = [
43995
- "$ErrorActionPreference = 'Stop'",
43996
- "$ProgressPreference = 'SilentlyContinue'",
43997
- `$action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument ${powershellString(`/d /v:off /s /c "${command}"`)}`,
43998
- `$trigger = New-ScheduledTaskTrigger -Daily -At '${job2.at}'`,
43999
- "$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
44000
- `Register-ScheduledTask -TaskName ${powershellString(task)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`
44001
- ].join(`
44002
+ var jscriptString = (value5) => JSON.stringify(value5).replaceAll(/[\u007f-\uffff]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
44003
+ function taskScheduler(file2) {
44004
+ return {
44005
+ name: "Task Scheduler task",
44006
+ install: (job) => quotable(job, /[\p{Cc}"%]/u, 'a control character, `"`, or `%`').pipe(exports_Effect.map((job2) => {
44007
+ const command = [
44008
+ ...exports_Option.toArray(job2.configHome).map((directory) => `set "XDG_CONFIG_HOME=${directory}"`),
44009
+ `set "PATH=${job2.nodeDirectory};%PATH%"`,
44010
+ `npx --yes ${packageSpec} ${["sync", ...job2.flags].map(cmdWord).join(" ")}`
44011
+ ].join(" && ");
44012
+ const script = [
44013
+ "$ErrorActionPreference = 'Stop'",
44014
+ "$ProgressPreference = 'SilentlyContinue'",
44015
+ `$action = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ${powershellString(`//B //Nologo //E:JScript "${file2}"`)}`,
44016
+ `$trigger = New-ScheduledTaskTrigger -Daily -At '${job2.at}'`,
44017
+ "$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
44018
+ `Register-ScheduledTask -TaskName ${powershellString(task)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`
44019
+ ].join(`
44002
44020
  `);
44003
- return [
44004
- Action3.Run({
44005
- program: "powershell.exe",
44006
- args: powershellArguments(script),
44007
- shown: `powershell.exe ${powershellOptions.join(" ")} <the script below, as UTF-16LE Base64>
44021
+ return [
44022
+ Action3.Write({
44023
+ file: file2,
44024
+ contents: `var shell = WScript.CreateObject("WScript.Shell");
44025
+ WScript.Quit(shell.Run(${jscriptString(`cmd.exe /d /v:off /s /c "${command}"`)}, 0, true));
44026
+ `
44027
+ }),
44028
+ Action3.Run({
44029
+ program: "powershell.exe",
44030
+ args: powershellArguments(script),
44031
+ shown: `powershell.exe ${powershellOptions.join(" ")} <the script below, as UTF-16LE Base64>
44008
44032
  ${script}`,
44009
- outcome: "required",
44010
- hint: "",
44011
- gone: []
44012
- })
44013
- ];
44014
- })),
44015
- uninstall: [
44016
- run6("reported", "schtasks.exe", ["/Delete", "/TN", task, "/F"]),
44017
- run6("absent", "schtasks.exe", ["/Query", "/TN", task], "The task is still registered; Task Scheduler's reason is shown above.")
44018
- ],
44019
- status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])]
44020
- };
44033
+ outcome: "required",
44034
+ hint: "",
44035
+ gone: []
44036
+ })
44037
+ ];
44038
+ })),
44039
+ uninstall: [
44040
+ run6("reported", "schtasks.exe", ["/Delete", "/TN", task, "/F"]),
44041
+ run6("absent", "schtasks.exe", ["/Query", "/TN", task], "The task is still registered; Task Scheduler's reason is shown above."),
44042
+ Action3.Remove({ file: file2 })
44043
+ ],
44044
+ status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])]
44045
+ };
44046
+ }
44021
44047
  var hostScheduler = exports_Effect.gen(function* () {
44022
44048
  const path = yield* exports_Path.Path;
44023
44049
  const home = homedir2();
44024
44050
  const units = exports_Option.getOrElse(yield* configHome, () => path.join(home, ".config"));
44025
- return yield* exports_Match.value(process.platform).pipe(exports_Match.when("linux", () => exports_Effect.succeed(systemdTimer(path.join(units, "systemd", "user")))), exports_Match.when("darwin", () => exports_Effect.succeed(launchAgent(home, userInfo().uid))), exports_Match.when("win32", () => exports_Effect.succeed(taskScheduler)), exports_Match.orElse((platform) => exports_Effect.fail(new ScheduleError({
44051
+ return yield* exports_Match.value(process.platform).pipe(exports_Match.when("linux", () => exports_Effect.succeed(systemdTimer(path.join(units, "systemd", "user")))), exports_Match.when("darwin", () => exports_Effect.succeed(launchAgent(home, userInfo().uid))), exports_Match.when("win32", () => exports_Effect.map(settingsDirectory, (directory) => taskScheduler(path.join(directory, `${unit}.js`)))), exports_Match.orElse((platform) => exports_Effect.fail(new ScheduleError({
44026
44052
  message: `No scheduler is supported on ${platform}; schedule token-ledger sync yourself.`
44027
44053
  }))));
44028
44054
  });
@@ -45594,6 +45620,17 @@ class SyncRejected extends exports_Schema.TaggedError()("SyncRejected", {
45594
45620
  }) {
45595
45621
  }
45596
45622
  var Acknowledgement = exports_Schema.Struct({ storedBuckets: exports_Schema.Natural });
45623
+ var MachineList = exports_Schema.Struct({
45624
+ staleAfterDays: exports_Schema.Number,
45625
+ from: exports_Schema.String,
45626
+ to: exports_Schema.String,
45627
+ machines: exports_Schema.Array(exports_Schema.Struct({ machineId: exports_Schema.String.check(exports_Schema.isUUID()) }))
45628
+ });
45629
+ function endpoint(server, path) {
45630
+ const base = new URL(server);
45631
+ base.pathname = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
45632
+ return new URL(path, base);
45633
+ }
45597
45634
  var VersionRejection = exports_Schema.Struct({ supportedVersions: exports_Schema.Array(exports_Schema.Int) });
45598
45635
  var readResponse = exports_Effect.fn("Sync.readResponse")(function* (response, version) {
45599
45636
  const status = response.status;
@@ -45615,9 +45652,7 @@ var readResponse = exports_Effect.fn("Sync.readResponse")(function* (response, v
45615
45652
  });
45616
45653
  var upload = exports_Effect.fn("Sync.upload")(function* (server, token, payload) {
45617
45654
  const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
45618
- const base = new URL(server);
45619
- base.pathname = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
45620
- const url = new URL(`ai-usage/machines/${payload.machine.id}/usage`, base);
45655
+ const url = endpoint(server, `ai-usage/machines/${payload.machine.id}/usage`);
45621
45656
  const request3 = yield* exports_HttpClientRequest.put(url).pipe(exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson, exports_HttpClientRequest.schemaBodyJson(SyncPayload)(payload), exports_Effect.orDie);
45622
45657
  return yield* client.execute(request3).pipe(exports_Effect.flatMap((response) => readResponse(response, payload.version)), exports_Effect.scoped, exports_Effect.timeout("60 seconds"), exports_Effect.catchTag(["HttpClientError", "TimeoutError"], () => exports_Effect.fail(new SyncUnreachable({ message: `Cannot reach ${url.origin}; try again later.` }))), exports_Effect.retry({
45623
45658
  while: exports_Predicate.isTagged("SyncUnreachable"),
@@ -45625,6 +45660,14 @@ var upload = exports_Effect.fn("Sync.upload")(function* (server, token, payload)
45625
45660
  times: 3
45626
45661
  }));
45627
45662
  });
45663
+ var hasUploaded = exports_Effect.fn("Sync.hasUploaded")(function* (server, token, id2) {
45664
+ const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
45665
+ const url = endpoint(server, "ai-usage/machines");
45666
+ const unanswered = new SyncUnreachable({
45667
+ message: `Could not ask ${url.origin} whether this machine has uploaded before.`
45668
+ });
45669
+ return yield* client.execute(exports_HttpClientRequest.get(url).pipe(exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson)).pipe(exports_Effect.filterOrFail((response) => response.status === 200, () => unanswered), exports_Effect.flatMap(exports_HttpClientResponse.schemaBodyJson(MachineList)), exports_Effect.map(({ machines }) => machines.some((machine) => machine.machineId.toLowerCase() === id2.toLowerCase())), exports_Effect.scoped, exports_Effect.timeout("20 seconds"), exports_Effect.provideService(exports_FetchHttpClient.RequestInit, { redirect: "error" }), exports_Effect.mapError(() => unanswered));
45670
+ });
45628
45671
 
45629
45672
  // packages/cli/src/main.ts
45630
45673
  class CliError2 extends exports_Schema.TaggedError()("CliError", { message: exports_Schema.String }) {
@@ -45748,7 +45791,7 @@ var serverFlag = exports_Flag.String("server").pipe(exports_Flag.withSchema(Serv
45748
45791
  var tokenFlag = exports_Flag.Redacted("token").pipe(exports_Flag.withFallbackConfig(exports_Config.Redacted("TOKI_API_TOKEN")), exports_Flag.optional);
45749
45792
  var claudeRetentionDays = 30;
45750
45793
  var sync6 = exports_Command.make("sync", {
45751
- ...usageFlags("13 days before --until", "Exit 2 without uploading for missing/partial sources or unpriced usage"),
45794
+ ...usageFlags("13 days before --until; a machine's first sync goes back to its earliest usage", "Exit 2 without uploading for missing/partial sources or unpriced usage"),
45752
45795
  server: serverFlag.pipe(exports_Flag.withDescription("toki2 URL; otherwise TOKEN_LEDGER_SERVER or sync.json")),
45753
45796
  token: tokenFlag.pipe(exports_Flag.withDescription("toki2 API token; prefer TOKI_API_TOKEN or sync.json")),
45754
45797
  dryRun: exports_Flag.Boolean("dry-run").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Print the payload as JSON and upload nothing"))
@@ -45758,42 +45801,69 @@ var sync6 = exports_Command.make("sync", {
45758
45801
  const { request: request3, today } = yield* usageRequest({ ...flags, source: exports_Option.none() }, (today2) => addDays(until ?? today2, -13));
45759
45802
  const machine = yield* loadMachine(directory);
45760
45803
  const ledger = yield* Ledger;
45761
- const payload = yield* ledger.syncPayload(request3, {
45762
- machine,
45763
- version: package_default.version
45764
- });
45765
- for (const entry of payload.coverage) {
45766
- if (entry.status !== "ok")
45767
- yield* exports_Console.error(`${entry.provider}: ${entry.status}; ${entry.files} files, ${entry.filesBeforeWindow ?? 0} older files not opened, ${entry.unreadable} unreadable, ${entry.malformedLines} malformed lines, ${entry.skippedRecords} skipped records.${entry.status === "failed" ? " Not uploaded; the server keeps its stored usage." : ""}`);
45768
- }
45769
- if (request3.sources.some((source) => source.provider === "claude") && request3.since < addDays(today, 1 - claudeRetentionDays))
45804
+ const client = { machine, version: package_default.version };
45805
+ const unsaved = {};
45806
+ const saved = exports_Option.isSome(flags.server) && exports_Option.isSome(flags.token) ? exports_Result.succeed(unsaved) : yield* loadSyncSettings(directory).pipe(exports_Effect.result);
45807
+ const settings = exports_Result.isSuccess(saved) ? saved.success : unsaved;
45808
+ const server = exports_Option.orElse(flags.server, () => exports_Option.fromUndefinedOr(settings.server));
45809
+ const token = exports_Option.orElse(flags.token, () => exports_Option.fromUndefinedOr(settings.token));
45810
+ const unlisted2 = exports_Option.isSome(flags.since) || exports_Option.isNone(server) || exports_Option.isNone(token) ? exports_Option.none() : yield* hasUploaded(server.value, token.value, machine.id).pipe(exports_Effect.map((listed2) => !listed2), exports_Effect.option);
45811
+ const whole = exports_Option.contains(unlisted2, true);
45812
+ const reachable = exports_Option.isSome(server) && exports_Option.isSome(token);
45813
+ if (exports_Option.isNone(unlisted2) && exports_Option.isNone(flags.since) && (reachable || flags.dryRun))
45814
+ yield* exports_Console.error(`${reachable ? "Could not ask the server whether this machine has uploaded before" : "No server and API token to ask whether this machine has uploaded before"}, so the window is ${request3.since} through ${request3.until}. If this is its first upload, send its earlier history with --since.`);
45815
+ const first = whole ? yield* ledger.historyPayload(request3, client) : { payload: yield* ledger.syncPayload(request3, client), since: request3.since };
45816
+ if (whole)
45817
+ yield* exports_Console.error(`First upload from this machine: taking in all the history found, from ${first.since}. Later syncs cover the last 14 days.${flags.provider === "all" ? "" : ` Only ${flags.provider} is included; the other tools' earlier history is not sent later by itself, so send it with --provider and --since.`}`);
45818
+ const examine = exports_Effect.fn("CLI.examine")(function* (payload) {
45819
+ for (const entry of payload.coverage) {
45820
+ if (entry.status !== "ok")
45821
+ yield* exports_Console.error(`${entry.provider}: ${entry.status}; ${entry.files} files, ${entry.filesBeforeWindow ?? 0} older files not opened, ${entry.unreadable} unreadable, ${entry.malformedLines} malformed lines, ${entry.skippedRecords} skipped records.${entry.status === "failed" ? " Not uploaded; the server keeps its stored usage." : ""}`);
45822
+ if (whole && entry.status === "failed")
45823
+ yield* exports_Console.error(`${entry.provider}: once its history can be read, send the earlier part with token-ledger sync --provider ${entry.provider} --since <first day>.`);
45824
+ }
45825
+ return payload.coverage.some((entry) => entry.status !== "ok") || payload.buckets.some((bucket) => bucket.unpricedRecords > 0);
45826
+ });
45827
+ const incomplete = yield* examine(first.payload);
45828
+ if (!whole && request3.sources.some((source) => source.provider === "claude") && request3.since < addDays(today, 1 - claudeRetentionDays))
45770
45829
  yield* exports_Console.error(`Warning: the window starts more than ${claudeRetentionDays} days ago. Claude Code deletes older transcripts by default, and the server replaces the whole window, so pruned history would lower its totals.`);
45771
- const incomplete = payload.coverage.some((entry) => entry.status !== "ok") || payload.buckets.some((bucket) => bucket.unpricedRecords > 0);
45772
45830
  if (flags.dryRun) {
45773
- yield* exports_Console.log(JSON.stringify(payload, null, 2));
45831
+ yield* exports_Console.log(JSON.stringify(first.payload, null, 2));
45774
45832
  if (flags.strict && incomplete)
45775
45833
  process.exitCode = 2;
45776
45834
  return;
45777
45835
  }
45778
- if (flags.strict && incomplete) {
45836
+ const refused = exports_Effect.gen(function* () {
45779
45837
  yield* exports_Console.error("Not syncing: coverage is incomplete or usage is unpriced (--strict).");
45780
45838
  process.exitCode = 2;
45781
- return;
45782
- }
45783
- const settings = exports_Option.isSome(flags.server) && exports_Option.isSome(flags.token) ? {} : yield* loadSyncSettings(directory);
45784
- const server = exports_Option.orElse(flags.server, () => exports_Option.fromUndefinedOr(settings.server));
45785
- const token = exports_Option.orElse(flags.token, () => exports_Option.fromUndefinedOr(settings.token));
45839
+ });
45840
+ if (flags.strict && incomplete)
45841
+ return yield* refused;
45842
+ if (exports_Result.isFailure(saved))
45843
+ return yield* exports_Effect.fail(saved.failure);
45786
45844
  if (exports_Option.isNone(server) || exports_Option.isNone(token))
45787
45845
  return yield* new CliError2({
45788
45846
  message: `Missing ${exports_Option.isNone(server) ? "server" : "API token"}: pass --server/--token, set TOKEN_LEDGER_SERVER/TOKI_API_TOKEN, or add it to ${directory}/sync.json.`
45789
45847
  });
45790
- const outcome = yield* upload(server.value, token.value, payload).pipe(exports_Effect.result);
45848
+ const send = (payload) => upload(server.value, token.value, payload).pipe(exports_Effect.result);
45849
+ const usual = exports_Effect.fn("CLI.usual")(function* (reason) {
45850
+ yield* exports_Console.error(`${reason} Uploading ${request3.since} through ${request3.until} instead; send earlier history in parts with --since and --until.`);
45851
+ const payload = yield* ledger.syncPayload(request3, client);
45852
+ return (yield* examine(payload)) && flags.strict ? exports_Option.none() : exports_Option.some({ sent: { payload, since: request3.since }, outcome: yield* send(payload) });
45853
+ });
45854
+ const still = !whole || !(yield* hasUploaded(server.value, token.value, machine.id).pipe(exports_Effect.orElseSucceed(() => true)));
45855
+ let result6 = still ? exports_Option.some({ sent: first, outcome: yield* send(first.payload) }) : yield* usual("This machine has uploaded since it was asked about.");
45856
+ if (whole && exports_Option.isSome(result6) && exports_Result.isFailure(result6.value.outcome) && exports_Match.value(result6.value.outcome.failure).pipe(exports_Match.tag("SyncRejected", () => still), exports_Match.orElse(() => false)))
45857
+ result6 = yield* usual(result6.value.outcome.failure.message);
45858
+ if (exports_Option.isNone(result6))
45859
+ return yield* refused;
45860
+ const { sent, outcome } = result6.value;
45791
45861
  if (exports_Result.isFailure(outcome)) {
45792
45862
  yield* exports_Console.error(outcome.failure.message);
45793
45863
  process.exitCode = exports_Match.value(outcome.failure).pipe(exports_Match.tag("SyncUnreachable", () => 3), exports_Match.tag("SyncUnauthorized", () => 4), exports_Match.tag("SyncUnsupportedVersion", () => 5), exports_Match.tag("SyncRejected", () => 6), exports_Match.exhaustive);
45794
45864
  return;
45795
45865
  }
45796
- yield* exports_Console.log(syncSummary(payload, request3, outcome.success));
45866
+ yield* exports_Console.log(syncSummary(sent.payload, { ...request3, since: sent.since }, outcome.success));
45797
45867
  })).pipe(exports_Command.withDescription("Upload hourly usage buckets from this machine to toki2; the server replaces the window"));
45798
45868
  var interactive = (prompt) => exports_Prompt.run(prompt).pipe(exports_Effect.mapError(() => new CliError2({
45799
45869
  message: "Nothing was saved. Without a terminal, pass --server and set TOKI_API_TOKEN."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ponbac/token-ledger",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Local AI token usage and API-equivalent cost reports by project",
5
5
  "license": "MIT",
6
6
  "engines": {