@ponbac/token-ledger 0.5.0 → 0.6.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.
Files changed (3) hide show
  1. package/README.md +22 -4
  2. package/dist/main.js +173 -70
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -451,6 +451,11 @@ Keep developer identity alongside exported reports when combining them across a
451
451
 
452
452
  ## Sync to toki2
453
453
 
454
+ Copilot requests routed through a ChatGPT OAuth proxy can use
455
+ [local billing hints](docs/billing-hints.md). On Windows the proxy appends metadata to
456
+ `%LOCALAPPDATA%\token-ledger\billing-hints\chatgpt-proxy.jsonl`; no path configuration
457
+ is needed. Usage stays attributed to Copilot, with ChatGPT/Codex as its subscription payer.
458
+
454
459
  `sync` uploads this machine's usage to a [toki2](https://github.com/ponbac/toki2)
455
460
  server, which combines every developer's machines for team reporting and billing.
456
461
  Run it on **every machine** where you use a coding agent, and schedule it daily.
@@ -524,6 +529,15 @@ does not keep a process running. Run it again to change the job.
524
529
  `journalctl --user -u token-ledger-sync` on Linux and in
525
530
  `~/Library/Logs/token-ledger-sync.log` on macOS.
526
531
 
532
+ On Windows, scheduled sync runs in the background without opening a terminal
533
+ window. A [Windows Script Host](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/wscript)
534
+ launcher in your token-ledger settings directory waits for sync to finish and
535
+ passes its exit code back to Task Scheduler. Windows Script Host must be enabled.
536
+ To update a task installed by an older CLI version, run
537
+ `npx.cmd --yes @ponbac/token-ledger@latest schedule install` again, including any
538
+ `--at`, `--config`, `--time-zone`, or `--provider` options you used before. This
539
+ replaces the existing task; your saved server and token are kept.
540
+
527
541
  | Platform | Scheduler | A missed run |
528
542
  | -------- | ------------------- | ------------------------------------------------------ |
529
543
  | Linux | systemd user timer | Runs within ten minutes of your next login |
@@ -632,13 +646,17 @@ but does not replay intervals missed while powered off.
632
646
  **Windows (Task Scheduler).** In PowerShell:
633
647
 
634
648
  ```powershell
635
- $action = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c npx --yes @ponbac/token-ledger@latest sync"
649
+ $runner = Join-Path $env:APPDATA "token-ledger\token-ledger-sync.js"
650
+ New-Item -ItemType Directory -Path (Split-Path $runner) -Force | Out-Null
651
+ '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
652
+ $action = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "//B //Nologo //E:JScript `"$runner`""
636
653
  $trigger = New-ScheduledTaskTrigger -Daily -At 12:30
637
654
  $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
638
- Register-ScheduledTask -TaskName "token-ledger sync" -Action $action -Trigger $trigger -Settings $settings
655
+ Register-ScheduledTask -TaskName "token-ledger sync" -Action $action -Trigger $trigger -Settings $settings -Force
639
656
  ```
640
657
 
641
- `-StartWhenAvailable` runs a missed sync at the next opportunity. The battery
658
+ The launcher hides the sync window and waits for its exit code. `//B` prevents
659
+ script dialogs. `-StartWhenAvailable` runs a missed sync at the next opportunity. The battery
642
660
  switches allow starts on battery and keep a running sync from being stopped when
643
661
  AC power disconnects. See [Task Scheduler settings](https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtasksettingsset).
644
662
 
@@ -749,7 +767,7 @@ For manual publication:
749
767
  1. Log in with `npm login` using an account with publish access to `@ponbac/token-ledger`.
750
768
  2. Run `bun run check`. The CLI test packs the package, installs it offline outside
751
769
  the repository with lifecycle scripts disabled, and exercises the installed CLI.
752
- 3. Run `bun run pack` to create `dist/ponbac-token-ledger-0.5.0.tgz` (filename follows version).
770
+ 3. Run `bun run pack` to create `dist/ponbac-token-ledger-0.6.0.tgz` (filename follows version).
753
771
  4. Inspect `npm publish ./dist/npm --dry-run`.
754
772
  5. Publish with `npm publish ./dist/npm --access public`; complete npm's authentication
755
773
  prompt if requested.
package/dist/main.js CHANGED
@@ -32686,8 +32686,48 @@ function dayWindow(since, until, timeZone) {
32686
32686
  };
32687
32687
  }
32688
32688
 
32689
+ // packages/core/src/billing-hints.ts
32690
+ class BillingHintsError extends exports_Schema.TaggedError()("BillingHintsError", {
32691
+ message: exports_Schema.String
32692
+ }) {
32693
+ }
32694
+ var Hint = exports_Schema.fromJsonString(exports_Schema.Struct({
32695
+ requestId: exports_Schema.NonEmptyString,
32696
+ billingProvider: exports_Schema.Literal("codex"),
32697
+ authMode: exports_Schema.Literal("chatgpt")
32698
+ }));
32699
+ var readBillingHints = exports_Effect.fn("BillingHints.read")(function* (location2) {
32700
+ const fs = yield* exports_FileSystem.FileSystem;
32701
+ const path = yield* exports_Path.Path;
32702
+ const entries3 = yield* fs.readDirectory(location2.directory).pipe(exports_Effect.result);
32703
+ if (exports_Result.isFailure(entries3)) {
32704
+ if (!location2.required && exports_Predicate.isTagged(entries3.failure.reason, "NotFound"))
32705
+ return new Set;
32706
+ return yield* new BillingHintsError({ message: "Cannot read the billing hints directory." });
32707
+ }
32708
+ const requests = new Set;
32709
+ for (const entry of entries3.success.toSorted()) {
32710
+ if (!entry.endsWith(".jsonl"))
32711
+ continue;
32712
+ const contents = yield* fs.readFileString(path.join(location2.directory, entry)).pipe(exports_Effect.mapError(() => new BillingHintsError({ message: `Cannot read ${JSON.stringify(entry)}.` })));
32713
+ let lineNumber = 0;
32714
+ for (const line of contents.split(`
32715
+ `)) {
32716
+ lineNumber++;
32717
+ if (!line.trim())
32718
+ continue;
32719
+ const hint = yield* exports_Schema.decodeUnknownEffect(Hint)(line).pipe(exports_Effect.mapError(() => new BillingHintsError({
32720
+ message: `Invalid row in ${JSON.stringify(entry)} at line ${lineNumber}.`
32721
+ })));
32722
+ requests.add(hint.requestId);
32723
+ }
32724
+ }
32725
+ return requests;
32726
+ });
32727
+
32689
32728
  // packages/core/src/model.ts
32690
32729
  var Provider = exports_Schema.Literals(["codex", "claude", "grok", "copilot", "pi"]);
32730
+ var BillingProvider = exports_Schema.Literals(["codex", "claude", "grok", "copilot"]);
32691
32731
  var Tokens = exports_Schema.Struct({
32692
32732
  input: exports_Schema.Natural,
32693
32733
  cacheRead: exports_Schema.Natural,
@@ -32713,6 +32753,7 @@ var ModelPrice = exports_Schema.Struct({
32713
32753
  cacheWrite: exports_Schema.NullOr(Rate)
32714
32754
  });
32715
32755
  var Configuration = exports_Schema.Struct({
32756
+ billingHintsDirectory: exports_Schema.optionalKey(exports_Schema.NonEmptyString),
32716
32757
  sources: exports_Schema.optionalKey(exports_Schema.Array(Source)),
32717
32758
  projects: exports_Schema.optionalKey(exports_Schema.Array(ProjectMapping)),
32718
32759
  prices: exports_Schema.optionalKey(exports_Schema.Record(exports_Schema.String, ModelPrice))
@@ -32729,6 +32770,7 @@ var Day = exports_Schema.String.check(exports_Schema.isPattern(/^\d{4}-\d{2}-\d{
32729
32770
  return Number.isFinite(date2.getTime()) && date2.toISOString().slice(0, 10) === s;
32730
32771
  }));
32731
32772
  var ReportRequest = exports_Schema.Struct({
32773
+ billingHints: exports_Schema.optionalKey(exports_Schema.Struct({ directory: exports_Schema.NonEmptyString, required: exports_Schema.Boolean })),
32732
32774
  since: Day,
32733
32775
  until: Day,
32734
32776
  timeZone: exports_Schema.TimeZoneNamed,
@@ -34689,7 +34731,7 @@ function repositoryReference(attributes) {
34689
34731
  const remote = attributes["copilot_chat.repo.remote_url"];
34690
34732
  return remote === undefined ? null : RepositoryReference.Remote({ value: remote });
34691
34733
  }
34692
- function copilotParser(file2) {
34734
+ function copilotParser(file2, chatgptRequests = new Set) {
34693
34735
  const spans = new Map;
34694
34736
  const candidates = [];
34695
34737
  const warning = "Copilot coverage starts when telemetry was enabled; only inference requests are counted.";
@@ -34732,7 +34774,7 @@ function copilotParser(file2) {
34732
34774
  const ms = span2.endTime[0] * 1000 + Math.floor(span2.endTime[1] / 1e6);
34733
34775
  if (!Number.isFinite(new Date(ms).getTime()))
34734
34776
  return skipped;
34735
- const record3 = {
34777
+ const base = {
34736
34778
  provider: "copilot",
34737
34779
  id: a["gen_ai.response.id"] === undefined ? `${span2.traceId}:${span2.spanId}` : `response:${a["gen_ai.response.id"]}`,
34738
34780
  session: a["gen_ai.conversation.id"] ?? a["session.id"] ?? file2,
@@ -34742,6 +34784,8 @@ function copilotParser(file2) {
34742
34784
  repository: repositoryReference(a),
34743
34785
  tokens: { input: input - cacheRead - cacheWrite, output, cacheRead, cacheWrite }
34744
34786
  };
34787
+ const responseId = a["gen_ai.response.id"];
34788
+ const record3 = responseId !== undefined && chatgptRequests.has(responseId) ? { ...base, billingProvider: "codex" } : base;
34745
34789
  candidates.push({ record: record3, spanKey, isSpan: exportedSpan !== null });
34746
34790
  return empty14;
34747
34791
  },
@@ -35023,6 +35067,7 @@ var SyncClient = exports_Schema.Struct({
35023
35067
  });
35024
35068
  var Cost = exports_Schema.Number.check(exports_Schema.isFinite(), exports_Schema.isGreaterThanOrEqualTo(0));
35025
35069
  var SyncBucket = exports_Schema.Struct({
35070
+ billingProvider: exports_Schema.optionalKey(BillingProvider),
35026
35071
  hourStart: UtcHour,
35027
35072
  sessionKey: SessionKey,
35028
35073
  project: NonEmptyText,
@@ -35032,7 +35077,7 @@ var SyncBucket = exports_Schema.Struct({
35032
35077
  records: exports_Schema.Int.check(exports_Schema.isGreaterThan(0)),
35033
35078
  estimatedCostUsd: exports_Schema.NullOr(Cost),
35034
35079
  unpricedRecords: exports_Schema.Natural
35035
- }).check(exports_Schema.makeFilter((bucket) => bucket.unpricedRecords <= bucket.records && bucket.estimatedCostUsd === null === bucket.unpricedRecords > 0));
35080
+ }).check(exports_Schema.makeFilter((bucket) => bucket.billingProvider !== bucket.provider && bucket.unpricedRecords <= bucket.records && bucket.estimatedCostUsd === null === bucket.unpricedRecords > 0));
35036
35081
  var SyncCoverage = exports_Schema.Struct({
35037
35082
  provider: Provider,
35038
35083
  status: Coverage.fields.status,
@@ -35052,7 +35097,7 @@ var ProviderHint = exports_Schema.Struct({
35052
35097
  plan: NonEmptyText
35053
35098
  });
35054
35099
  var SyncPayload = exports_Schema.Struct({
35055
- version: exports_Schema.Literal(1),
35100
+ version: exports_Schema.Literals([1, 2]),
35056
35101
  machine: SyncMachine,
35057
35102
  clientVersion: NonEmptyText,
35058
35103
  timeZone: NonEmptyText,
@@ -35067,11 +35112,12 @@ var SyncPayload = exports_Schema.Struct({
35067
35112
  buckets: exports_Schema.Array(SyncBucket),
35068
35113
  coverage: exports_Schema.Array(SyncCoverage),
35069
35114
  providerHints: exports_Schema.optionalKey(exports_Schema.Array(ProviderHint))
35070
- }).check(exports_Schema.makeFilter((payload) => distinct(payload.buckets, (bucket) => JSON.stringify([
35115
+ }).check(exports_Schema.makeFilter((payload) => (payload.version === 2 || payload.buckets.every((bucket) => bucket.billingProvider === undefined)) && distinct(payload.buckets, (bucket) => JSON.stringify([
35071
35116
  bucket.hourStart,
35072
35117
  bucket.sessionKey,
35073
35118
  bucket.project,
35074
35119
  bucket.provider,
35120
+ bucket.billingProvider ?? null,
35075
35121
  bucket.model
35076
35122
  ])) && distinct(payload.coverage, (entry) => entry.provider) && distinct(payload.providerHints ?? [], (hint) => JSON.stringify([hint.provider, hint.hourStart, hint.plan])), { expected: "unique bucket keys, coverage providers, and plan hints" }), exports_Schema.makeFilter((payload) => {
35077
35123
  const replaced = replacedProviders(payload.coverage);
@@ -35097,7 +35143,14 @@ function sessionBuckets(pricing) {
35097
35143
  const hourStart = Math.floor(record3.timestamp / hour) * hour;
35098
35144
  const project = storable(name);
35099
35145
  const model = storable(record3.model);
35100
- const key = JSON.stringify([hourStart, record3.provider, record3.session, project, model]);
35146
+ const key = JSON.stringify([
35147
+ hourStart,
35148
+ record3.provider,
35149
+ record3.billingProvider ?? null,
35150
+ record3.session,
35151
+ project,
35152
+ model
35153
+ ]);
35101
35154
  const previous = totals.get(key);
35102
35155
  const cost = priceTokens(record3.tokens, lookupPrice(pricing, record3.model));
35103
35156
  totals.set(key, {
@@ -35109,17 +35162,20 @@ function sessionBuckets(pricing) {
35109
35162
  });
35110
35163
  },
35111
35164
  finish() {
35112
- return [...totals.values()].map(({ record: record3, project, model, hourStart, usage }) => ({
35113
- hourStart: new Date(hourStart).toISOString(),
35114
- sessionKey: sessionKey(record3.provider, record3.session),
35115
- project,
35116
- provider: record3.provider,
35117
- model,
35118
- tokens: usage.tokens,
35119
- records: usage.records,
35120
- estimatedCostUsd: usage.estimatedCostUsd,
35121
- unpricedRecords: usage.unpricedRecords
35122
- })).toSorted((a, b) => a.hourStart.localeCompare(b.hourStart) || a.provider.localeCompare(b.provider) || a.sessionKey.localeCompare(b.sessionKey) || a.project.localeCompare(b.project) || a.model.localeCompare(b.model));
35165
+ return [...totals.values()].map(({ record: record3, project, model, hourStart, usage }) => {
35166
+ const bucket = {
35167
+ hourStart: new Date(hourStart).toISOString(),
35168
+ sessionKey: sessionKey(record3.provider, record3.session),
35169
+ project,
35170
+ provider: record3.provider,
35171
+ model,
35172
+ tokens: usage.tokens,
35173
+ records: usage.records,
35174
+ estimatedCostUsd: usage.estimatedCostUsd,
35175
+ unpricedRecords: usage.unpricedRecords
35176
+ };
35177
+ return record3.billingProvider === undefined ? bucket : { ...bucket, billingProvider: record3.billingProvider };
35178
+ }).toSorted((a, b) => a.hourStart.localeCompare(b.hourStart) || a.provider.localeCompare(b.provider) || a.sessionKey.localeCompare(b.sessionKey) || a.project.localeCompare(b.project) || a.model.localeCompare(b.model) || (a.billingProvider ?? "").localeCompare(b.billingProvider ?? ""));
35123
35179
  }
35124
35180
  };
35125
35181
  }
@@ -35177,14 +35233,18 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35177
35233
  const request3 = yield* exports_Schema.decodeUnknownEffect(ReportRequest)(input).pipe(exports_Effect.mapError(() => new InvalidRequest({
35178
35234
  message: "Expected an ordered inclusive day window, a named time zone, and valid sources, mappings, and prices."
35179
35235
  })));
35180
- if (request3.sources.some((source) => !path.isAbsolute(source.path)) || request3.projects.some((mapping) => mapping.paths.some((prefix3) => !path.isAbsolute(prefix3)))) {
35236
+ if (request3.billingHints !== undefined && !path.isAbsolute(request3.billingHints.directory) || request3.sources.some((source) => !path.isAbsolute(source.path)) || request3.projects.some((mapping) => mapping.paths.some((prefix3) => !path.isAbsolute(prefix3)))) {
35181
35237
  return yield* new InvalidRequest({
35182
- message: "Source and project mapping paths must be absolute."
35238
+ message: "Source, billing hint, and project mapping paths must be absolute."
35183
35239
  });
35184
35240
  }
35185
35241
  return request3;
35186
35242
  });
35187
- const scan2 = exports_Effect.fn("Ledger.scan")(function* (request3, start, locate, collect2, notice) {
35243
+ const scan2 = exports_Effect.fn("Ledger.scan")(function* (request3, start, locate, collect2, notice, onWarning) {
35244
+ const hints = yield* (notice !== undefined && request3.billingHints !== undefined && request3.sources.some((source) => source.provider === "copilot") ? readBillingHints(request3.billingHints).pipe(exports_Effect.provideService(exports_FileSystem.FileSystem, fs), exports_Effect.provideService(exports_Path.Path, path)) : exports_Effect.succeed(new Set)).pipe(exports_Effect.result);
35245
+ const chatgptRequests = exports_Result.isSuccess(hints) ? hints.success : new Set;
35246
+ if (exports_Result.isFailure(hints))
35247
+ yield* onWarning?.(`Billing hints: ${hints.failure.message} Copilot will not be uploaded. Repair the hints and rerun sync with --since <first missed day>.`) ?? exports_Effect.void;
35188
35248
  const resolveProject = yield* projectResolver(request3.projects).pipe(exports_Effect.provideService(exports_FileSystem.FileSystem, fs), exports_Effect.provideService(exports_Path.Path, path));
35189
35249
  const seen = new Set;
35190
35250
  const visitedFiles = new Set;
@@ -35200,7 +35260,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35200
35260
  let failedFiles = 0;
35201
35261
  let missingRoot = false;
35202
35262
  const warnings = new Set;
35203
- const copilot = source.provider === "copilot" ? copilotParser(source.path) : undefined;
35263
+ const copilot = source.provider === "copilot" ? copilotParser(source.path, chatgptRequests) : undefined;
35204
35264
  const place = exports_Effect.fn("Ledger.placeRecord")(function* (record3, slot) {
35205
35265
  const id2 = `${record3.provider}:${record3.id}`;
35206
35266
  if (seen.has(id2)) {
@@ -35286,14 +35346,17 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35286
35346
  }
35287
35347
  if (copilot?.finish !== undefined)
35288
35348
  yield* accept2(copilot.finish());
35289
- const status = missingRoot ? "missing" : failedFiles > 0 && files === 0 ? "failed" : failedFiles > 0 || malformedLines > 0 || skippedRecords > 0 ? "partial" : "ok";
35349
+ const hintsFailed = source.provider === "copilot" && exports_Result.isFailure(hints);
35350
+ if (hintsFailed)
35351
+ warnings.add("Billing hints could not be read; stored Copilot usage will be kept.");
35352
+ const status = hintsFailed ? "failed" : missingRoot ? "missing" : failedFiles > 0 && files === 0 ? "failed" : failedFiles > 0 || malformedLines > 0 || skippedRecords > 0 ? "partial" : "ok";
35290
35353
  coverage.push(() => ({
35291
35354
  provider: source.provider,
35292
35355
  source: source.path,
35293
35356
  status,
35294
35357
  files,
35295
35358
  filesBeforeWindow,
35296
- unreadable: missingRoot ? 0 : failedFiles,
35359
+ unreadable: (missingRoot ? 0 : failedFiles) + (hintsFailed ? 1 : 0),
35297
35360
  malformedLines,
35298
35361
  skippedRecords,
35299
35362
  duplicates,
@@ -35336,7 +35399,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35336
35399
  coverage
35337
35400
  });
35338
35401
  });
35339
- const payloadFrom = exports_Effect.fn("Ledger.payloadFrom")(function* (input, clientInput, history) {
35402
+ const payloadFrom = exports_Effect.fn("Ledger.payloadFrom")(function* (input, clientInput, history, onWarning) {
35340
35403
  const request3 = yield* decode5(input);
35341
35404
  const client = yield* exports_Schema.decodeUnknownEffect(SyncClient)(clientInput).pipe(exports_Effect.mapError(() => new InvalidRequest({
35342
35405
  message: "Expected a machine UUID and label and a client version."
@@ -35352,13 +35415,14 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35352
35415
  }, (plan) => {
35353
35416
  earliest = Math.min(earliest, plan.timestamp);
35354
35417
  hints.add(plan);
35355
- });
35418
+ }, onWarning);
35356
35419
  const since = earliest < requested.start ? exports_DateTime.formatIsoDate(exports_DateTime.setZone(exports_DateTime.makeUnsafe(earliest), request3.timeZone)) : request3.since;
35357
35420
  const window = since === request3.since ? requested : hourRange(dayWindow(since, request3.until, request3.timeZone));
35358
35421
  const summary = providerCoverage(coverage);
35359
35422
  const replaced = replacedProviders(summary);
35423
+ const uploadedBuckets = buckets.finish().filter((bucket) => replaced.has(bucket.provider));
35360
35424
  const payload = yield* SyncPayload.makeEffect({
35361
- version: 1,
35425
+ version: uploadedBuckets.some((bucket) => bucket.billingProvider !== undefined) ? 2 : 1,
35362
35426
  machine: client.machine,
35363
35427
  clientVersion: client.version,
35364
35428
  timeZone: request3.timeZone.id,
@@ -35373,7 +35437,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35373
35437
  fetchedAt: request3.pricing.fetchedAt,
35374
35438
  source: request3.pricing.source
35375
35439
  },
35376
- buckets: buckets.finish().filter((bucket) => replaced.has(bucket.provider)),
35440
+ buckets: uploadedBuckets,
35377
35441
  coverage: summary,
35378
35442
  providerHints: hints.finish().filter((hint) => replaced.has(hint.provider))
35379
35443
  }).pipe(exports_Effect.mapError(() => new InvalidRequest({
@@ -35383,8 +35447,8 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35383
35447
  });
35384
35448
  return Ledger.of({
35385
35449
  report,
35386
- syncPayload: (request3, client) => exports_Effect.map(payloadFrom(request3, client, false), ({ payload }) => payload),
35387
- historyPayload: (request3, client) => payloadFrom(request3, client, true)
35450
+ syncPayload: (request3, client, onWarning) => exports_Effect.map(payloadFrom(request3, client, false, onWarning), ({ payload }) => payload),
35451
+ historyPayload: (request3, client, onWarning) => payloadFrom(request3, client, true, onWarning)
35388
35452
  });
35389
35453
  }));
35390
35454
  }
@@ -42699,7 +42763,7 @@ var runWith2 = (command, config) => {
42699
42763
  // packages/cli/package.json
42700
42764
  var package_default = {
42701
42765
  name: "@ponbac/token-ledger",
42702
- version: "0.5.0",
42766
+ version: "0.6.0",
42703
42767
  private: true,
42704
42768
  type: "module",
42705
42769
  bin: {
@@ -42728,6 +42792,18 @@ var package_default = {
42728
42792
  url: "https://github.com/ponbac/token-ledger/issues"
42729
42793
  }
42730
42794
  };
42795
+
42796
+ // packages/cli/src/billing-hints.ts
42797
+ import { posix as posix2, win32 as win322 } from "node:path";
42798
+ var dataHome = exports_Effect.gen(function* () {
42799
+ const path = yield* exports_Path.Path;
42800
+ return yield* exports_Config.String("XDG_DATA_HOME").pipe(exports_Config.option, exports_Effect.map(exports_Option.filter((directory) => path.isAbsolute(directory))));
42801
+ });
42802
+ function billingHintsDirectory(platform, home, localAppData, xdgDataHome) {
42803
+ const path = platform === "win32" ? win322 : posix2;
42804
+ const root = exports_Match.value(platform).pipe(exports_Match.when("win32", () => exports_Option.getOrElse(exports_Option.filter(localAppData, (directory) => path.isAbsolute(directory)), () => path.join(home, "AppData", "Local"))), exports_Match.when("darwin", () => path.join(home, "Library", "Application Support")), exports_Match.orElse(() => exports_Option.getOrElse(xdgDataHome, () => path.join(home, ".local", "share"))));
42805
+ return path.join(root, "token-ledger", "billing-hints");
42806
+ }
42731
42807
  // node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
42732
42808
  function createScanner(text2, ignoreTrivia = false) {
42733
42809
  const len = text2.length;
@@ -43875,7 +43951,12 @@ function run6(outcome, program, args2, hint = "") {
43875
43951
  });
43876
43952
  }
43877
43953
  function quotable(job, forbidden2, described) {
43878
- const offending = [job.nodeDirectory, ...exports_Option.toArray(job.configHome), ...job.flags].find((value5) => forbidden2.test(value5));
43954
+ const offending = [
43955
+ job.nodeDirectory,
43956
+ ...exports_Option.toArray(job.configHome),
43957
+ ...exports_Option.toArray(job.dataHome),
43958
+ ...job.flags
43959
+ ].find((value5) => forbidden2.test(value5));
43879
43960
  return offending === undefined ? exports_Effect.succeed(job) : exports_Effect.fail(new ScheduleError({
43880
43961
  message: `Cannot schedule with ${JSON.stringify(offending)}: it contains ${described}.`
43881
43962
  }));
@@ -43884,6 +43965,7 @@ var posixWord = (value5) => /^[\w@+=:,./-]+$/.test(value5) ? value5 : `'${value5
43884
43965
  var posixScript = (job) => [
43885
43966
  "cd /",
43886
43967
  ...exports_Option.toArray(job.configHome).map((directory) => `export XDG_CONFIG_HOME=${posixWord(directory)}`),
43968
+ ...exports_Option.toArray(job.dataHome).map((directory) => `export XDG_DATA_HOME=${posixWord(directory)}`),
43887
43969
  `export PATH=${posixWord(job.nodeDirectory)}:"$PATH"`,
43888
43970
  `exec npx --yes ${packageSpec} ${["sync", ...job.flags].map(posixWord).join(" ")}`
43889
43971
  ].join("; ");
@@ -43999,46 +44081,56 @@ var powershellArguments = (script) => [
43999
44081
  ...powershellOptions,
44000
44082
  Buffer.from(script, "utf16le").toString("base64")
44001
44083
  ];
44002
- var taskScheduler = {
44003
- name: "Task Scheduler task",
44004
- install: (job) => quotable(job, /[\p{Cc}"%]/u, 'a control character, `"`, or `%`').pipe(exports_Effect.map((job2) => {
44005
- const command = [
44006
- ...exports_Option.toArray(job2.configHome).map((directory) => `set "XDG_CONFIG_HOME=${directory}"`),
44007
- `set "PATH=${job2.nodeDirectory};%PATH%"`,
44008
- `npx --yes ${packageSpec} ${["sync", ...job2.flags].map(cmdWord).join(" ")}`
44009
- ].join(" && ");
44010
- const script = [
44011
- "$ErrorActionPreference = 'Stop'",
44012
- "$ProgressPreference = 'SilentlyContinue'",
44013
- `$action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument ${powershellString(`/d /v:off /s /c "${command}"`)}`,
44014
- `$trigger = New-ScheduledTaskTrigger -Daily -At '${job2.at}'`,
44015
- "$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
44016
- `Register-ScheduledTask -TaskName ${powershellString(task)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`
44017
- ].join(`
44084
+ var jscriptString = (value5) => JSON.stringify(value5).replaceAll(/[\u007f-\uffff]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
44085
+ function taskScheduler(file2) {
44086
+ return {
44087
+ name: "Task Scheduler task",
44088
+ install: (job) => quotable(job, /[\p{Cc}"%]/u, 'a control character, `"`, or `%`').pipe(exports_Effect.map((job2) => {
44089
+ const command = [
44090
+ ...exports_Option.toArray(job2.configHome).map((directory) => `set "XDG_CONFIG_HOME=${directory}"`),
44091
+ `set "PATH=${job2.nodeDirectory};%PATH%"`,
44092
+ `npx --yes ${packageSpec} ${["sync", ...job2.flags].map(cmdWord).join(" ")}`
44093
+ ].join(" && ");
44094
+ const script = [
44095
+ "$ErrorActionPreference = 'Stop'",
44096
+ "$ProgressPreference = 'SilentlyContinue'",
44097
+ `$action = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ${powershellString(`//B //Nologo //E:JScript "${file2}"`)}`,
44098
+ `$trigger = New-ScheduledTaskTrigger -Daily -At '${job2.at}'`,
44099
+ "$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
44100
+ `Register-ScheduledTask -TaskName ${powershellString(task)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`
44101
+ ].join(`
44018
44102
  `);
44019
- return [
44020
- Action3.Run({
44021
- program: "powershell.exe",
44022
- args: powershellArguments(script),
44023
- shown: `powershell.exe ${powershellOptions.join(" ")} <the script below, as UTF-16LE Base64>
44103
+ return [
44104
+ Action3.Write({
44105
+ file: file2,
44106
+ contents: `var shell = WScript.CreateObject("WScript.Shell");
44107
+ WScript.Quit(shell.Run(${jscriptString(`cmd.exe /d /v:off /s /c "${command}"`)}, 0, true));
44108
+ `
44109
+ }),
44110
+ Action3.Run({
44111
+ program: "powershell.exe",
44112
+ args: powershellArguments(script),
44113
+ shown: `powershell.exe ${powershellOptions.join(" ")} <the script below, as UTF-16LE Base64>
44024
44114
  ${script}`,
44025
- outcome: "required",
44026
- hint: "",
44027
- gone: []
44028
- })
44029
- ];
44030
- })),
44031
- uninstall: [
44032
- run6("reported", "schtasks.exe", ["/Delete", "/TN", task, "/F"]),
44033
- run6("absent", "schtasks.exe", ["/Query", "/TN", task], "The task is still registered; Task Scheduler's reason is shown above.")
44034
- ],
44035
- status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])]
44036
- };
44115
+ outcome: "required",
44116
+ hint: "",
44117
+ gone: []
44118
+ })
44119
+ ];
44120
+ })),
44121
+ uninstall: [
44122
+ run6("reported", "schtasks.exe", ["/Delete", "/TN", task, "/F"]),
44123
+ run6("absent", "schtasks.exe", ["/Query", "/TN", task], "The task is still registered; Task Scheduler's reason is shown above."),
44124
+ Action3.Remove({ file: file2 })
44125
+ ],
44126
+ status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])]
44127
+ };
44128
+ }
44037
44129
  var hostScheduler = exports_Effect.gen(function* () {
44038
44130
  const path = yield* exports_Path.Path;
44039
44131
  const home = homedir2();
44040
44132
  const units = exports_Option.getOrElse(yield* configHome, () => path.join(home, ".config"));
44041
- 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({
44133
+ 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({
44042
44134
  message: `No scheduler is supported on ${platform}; schedule token-ledger sync yourself.`
44043
44135
  }))));
44044
44136
  });
@@ -44164,13 +44256,13 @@ var startupSteps = exports_Effect.fn("Copilot.startupSteps")(function* (host, ta
44164
44256
  onSome: (file3) => path.basename(file3)
44165
44257
  });
44166
44258
  const exported = `export ${variable}=${homeWord(path, host, target, posixWord)}`;
44167
- const posix2 = (file3) => ({
44259
+ const posix3 = (file3) => ({
44168
44260
  file: file3,
44169
44261
  line: exported,
44170
44262
  satisfies: exportsTo(target, host.home),
44171
44263
  others: []
44172
44264
  });
44173
- const startup = yield* exports_Match.value(shell).pipe(exports_Match.when("zsh", () => exports_Effect.succeed(exports_Option.some(posix2(path.join(exports_Option.getOrElse(host.zshDirectory, () => host.home), ".zshrc"))))), exports_Match.when("bash", () => exports_Effect.map(bashStartup(host), (file3) => exports_Option.some(posix2(file3)))), exports_Match.when("fish", () => {
44265
+ const startup = yield* exports_Match.value(shell).pipe(exports_Match.when("zsh", () => exports_Effect.succeed(exports_Option.some(posix3(path.join(exports_Option.getOrElse(host.zshDirectory, () => host.home), ".zshrc"))))), exports_Match.when("bash", () => exports_Effect.map(bashStartup(host), (file3) => exports_Option.some(posix3(file3)))), exports_Match.when("fish", () => {
44174
44266
  const directory = path.join(exports_Option.getOrElse(host.configHome, () => path.join(host.home, ".config")), "fish");
44175
44267
  const line2 = `set -gx ${variable} ${homeWord(path, host, target, fishWord)}`;
44176
44268
  const snippets = path.join(directory, "conf.d");
@@ -45637,7 +45729,7 @@ var readResponse = exports_Effect.fn("Sync.readResponse")(function* (response, v
45637
45729
  status,
45638
45730
  message: "This API token may not upload for this machine ID."
45639
45731
  }))), exports_Match.when(422, () => exports_HttpClientResponse.schemaBodyJson(VersionRejection)(response).pipe(exports_Effect.mapError(() => new SyncRejected({ status, message: `The server rejected the upload (${status}).` })), exports_Effect.flatMap((rejection) => exports_Effect.fail(rejection.supportedVersions.includes(version) ? new SyncRejected({ status, message: `The server rejected the upload (${status}).` }) : new SyncUnsupportedVersion({
45640
- message: `The server accepts payload versions ${rejection.supportedVersions.join(", ") || "none"}, not ${version}; upgrade token-ledger.`
45732
+ message: `The server accepts payload versions ${rejection.supportedVersions.join(", ") || "none"}, not ${version}; update Toki or use a compatible token-ledger version.`
45641
45733
  }))))), exports_Match.orElse(() => exports_Effect.fail(new SyncRejected({ status, message: `The server rejected the upload (${status}).` }))));
45642
45734
  });
45643
45735
  var upload = exports_Effect.fn("Sync.upload")(function* (server, token, payload) {
@@ -45750,6 +45842,13 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
45750
45842
  if (pricing.status === "unavailable")
45751
45843
  yield* exports_Console.error("Pricing unavailable: unknown rates remain unpriced. Configure prices or rerun online.");
45752
45844
  const request3 = yield* ReportRequest.makeEffect({
45845
+ billingHints: configuration.billingHintsDirectory === undefined ? {
45846
+ directory: billingHintsDirectory(process.platform, home, yield* exports_Config.String("LOCALAPPDATA").pipe(exports_Config.option), yield* dataHome),
45847
+ required: false
45848
+ } : {
45849
+ directory: expand(configuration.billingHintsDirectory, path.dirname(configFile)),
45850
+ required: true
45851
+ },
45753
45852
  since: exports_Option.getOrElse(flags.since, () => defaultSince(today)),
45754
45853
  until: exports_Option.getOrElse(flags.until, () => today),
45755
45854
  timeZone,
@@ -45802,7 +45901,10 @@ var sync6 = exports_Command.make("sync", {
45802
45901
  const reachable = exports_Option.isSome(server) && exports_Option.isSome(token);
45803
45902
  if (exports_Option.isNone(unlisted2) && exports_Option.isNone(flags.since) && (reachable || flags.dryRun))
45804
45903
  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.`);
45805
- const first = whole ? yield* ledger.historyPayload(request3, client) : { payload: yield* ledger.syncPayload(request3, client), since: request3.since };
45904
+ const first = whole ? yield* ledger.historyPayload(request3, client, exports_Console.error) : {
45905
+ payload: yield* ledger.syncPayload(request3, client, exports_Console.error),
45906
+ since: request3.since
45907
+ };
45806
45908
  if (whole)
45807
45909
  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.`}`);
45808
45910
  const examine = exports_Effect.fn("CLI.examine")(function* (payload) {
@@ -45838,7 +45940,7 @@ var sync6 = exports_Command.make("sync", {
45838
45940
  const send = (payload) => upload(server.value, token.value, payload).pipe(exports_Effect.result);
45839
45941
  const usual = exports_Effect.fn("CLI.usual")(function* (reason) {
45840
45942
  yield* exports_Console.error(`${reason} Uploading ${request3.since} through ${request3.until} instead; send earlier history in parts with --since and --until.`);
45841
- const payload = yield* ledger.syncPayload(request3, client);
45943
+ const payload = yield* ledger.syncPayload(request3, client, exports_Console.error);
45842
45944
  return (yield* examine(payload)) && flags.strict ? exports_Option.none() : exports_Option.some({ sent: { payload, since: request3.since }, outcome: yield* send(payload) });
45843
45945
  });
45844
45946
  const still = !whole || !(yield* hasUploaded(server.value, token.value, machine.id).pipe(exports_Effect.orElseSucceed(() => true)));
@@ -45894,6 +45996,7 @@ var scheduleInstall = exports_Command.make("install", {
45894
45996
  at: flags.at,
45895
45997
  nodeDirectory: path.dirname(process.execPath),
45896
45998
  configHome: yield* configHome,
45999
+ dataHome: yield* dataHome,
45897
46000
  flags: [
45898
46001
  ...exports_Option.match(config, { onNone: () => [], onSome: (file2) => ["--config", file2] }),
45899
46002
  ...exports_Option.match(flags.timeZone, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ponbac/token-ledger",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Local AI token usage and API-equivalent cost reports by project",
5
5
  "license": "MIT",
6
6
  "engines": {