@ponbac/token-ledger 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +117 -23
- package/dist/main.js +1289 -212
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -32753,12 +32753,25 @@ var ProjectMapping = exports_Schema.Struct({
|
|
|
32753
32753
|
repositories: exports_Schema.Array(exports_Schema.NonEmptyString)
|
|
32754
32754
|
});
|
|
32755
32755
|
var Rate = exports_Schema.Number.check(exports_Schema.isFinite(), exports_Schema.isGreaterThanOrEqualTo(0));
|
|
32756
|
-
var
|
|
32756
|
+
var rateFields = {
|
|
32757
32757
|
input: Rate,
|
|
32758
32758
|
output: Rate,
|
|
32759
32759
|
cacheRead: exports_Schema.NullOr(Rate),
|
|
32760
|
-
cacheWrite: exports_Schema.NullOr(Rate)
|
|
32760
|
+
cacheWrite: exports_Schema.NullOr(Rate),
|
|
32761
|
+
cacheWrite1h: exports_Schema.optionalKey(Rate)
|
|
32762
|
+
};
|
|
32763
|
+
var Rates = exports_Schema.Struct(rateFields);
|
|
32764
|
+
var PriceTier = exports_Schema.Struct({
|
|
32765
|
+
above: exports_Schema.Int.check(exports_Schema.isGreaterThan(0)),
|
|
32766
|
+
...rateFields
|
|
32761
32767
|
});
|
|
32768
|
+
var UncachedInput = exports_Schema.Literals(["cacheWrite", "input"]);
|
|
32769
|
+
var ModelPrice = exports_Schema.Struct({
|
|
32770
|
+
...rateFields,
|
|
32771
|
+
tiers: exports_Schema.optionalKey(exports_Schema.Array(PriceTier)),
|
|
32772
|
+
uncachedInput: exports_Schema.optionalKey(UncachedInput)
|
|
32773
|
+
}).check(exports_Schema.makeFilter((price) => new Set((price.tiers ?? []).map((tier) => tier.above)).size === (price.tiers ?? []).length, { expected: "long-context tiers with distinct thresholds" }));
|
|
32774
|
+
var PricingBasis = exports_Schema.String.check(exports_Schema.isPattern(/^[\x21-\x7e]{1,128}$/));
|
|
32762
32775
|
var Configuration = exports_Schema.Struct({
|
|
32763
32776
|
billingHintsDirectory: exports_Schema.optionalKey(exports_Schema.NonEmptyString),
|
|
32764
32777
|
sources: exports_Schema.optionalKey(exports_Schema.Array(Source)),
|
|
@@ -32769,7 +32782,8 @@ var PriceBook = exports_Schema.Struct({
|
|
|
32769
32782
|
status: exports_Schema.Literals(["fresh", "cached", "unavailable", "custom"]),
|
|
32770
32783
|
fetchedAt: exports_Schema.NullOr(exports_Schema.String),
|
|
32771
32784
|
source: exports_Schema.String,
|
|
32772
|
-
prices: exports_Schema.Record(exports_Schema.String, ModelPrice)
|
|
32785
|
+
prices: exports_Schema.Record(exports_Schema.String, ModelPrice),
|
|
32786
|
+
basis: exports_Schema.optionalKey(PricingBasis)
|
|
32773
32787
|
});
|
|
32774
32788
|
var RepositoryReference = exports_Data.taggedEnum();
|
|
32775
32789
|
var Day = exports_Schema.String.check(exports_Schema.isPattern(/^\d{4}-\d{2}-\d{2}$/), exports_Schema.makeFilter((s) => {
|
|
@@ -32802,7 +32816,7 @@ var ReportRow = exports_Schema.Struct({
|
|
|
32802
32816
|
day: Day,
|
|
32803
32817
|
provider: Provider,
|
|
32804
32818
|
model: exports_Schema.String,
|
|
32805
|
-
pricePerMillion: exports_Schema.NullOr(
|
|
32819
|
+
pricePerMillion: exports_Schema.NullOr(Rates),
|
|
32806
32820
|
tokens: Tokens,
|
|
32807
32821
|
records: exports_Schema.Natural,
|
|
32808
32822
|
estimatedCostUsd: exports_Schema.NullOr(exports_Schema.Number),
|
|
@@ -32819,7 +32833,8 @@ var UsageReport = exports_Schema.Struct({
|
|
|
32819
32833
|
pricing: exports_Schema.Struct({
|
|
32820
32834
|
status: PriceBook.fields.status,
|
|
32821
32835
|
fetchedAt: PriceBook.fields.fetchedAt,
|
|
32822
|
-
source: exports_Schema.String
|
|
32836
|
+
source: exports_Schema.String,
|
|
32837
|
+
basis: PriceBook.fields.basis
|
|
32823
32838
|
}),
|
|
32824
32839
|
rows: exports_Schema.Array(ReportRow),
|
|
32825
32840
|
coverage: exports_Schema.Array(Coverage)
|
|
@@ -32836,6 +32851,9 @@ function addTokens(a, b) {
|
|
|
32836
32851
|
function totalTokens(tokens) {
|
|
32837
32852
|
return tokens.input + tokens.cacheRead + tokens.cacheWrite + tokens.output;
|
|
32838
32853
|
}
|
|
32854
|
+
|
|
32855
|
+
// packages/core/src/pricing.ts
|
|
32856
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
32839
32857
|
// node_modules/.bun/effect@4.0.0/node_modules/effect/dist/http/FetchHttpClient.js
|
|
32840
32858
|
var exports_FetchHttpClient = {};
|
|
32841
32859
|
__export(exports_FetchHttpClient, {
|
|
@@ -34289,21 +34307,555 @@ var fetch = /* @__PURE__ */ make48((request3, url, signal, fiber3) => {
|
|
|
34289
34307
|
return send(undefined);
|
|
34290
34308
|
});
|
|
34291
34309
|
var layer14 = /* @__PURE__ */ layerMergedContext(/* @__PURE__ */ succeed6(fetch));
|
|
34310
|
+
// packages/core/src/copilot-rates.json
|
|
34311
|
+
var copilot_rates_default = {
|
|
34312
|
+
version: "2026-10-24",
|
|
34313
|
+
description: "GitHub Copilot's AI credit rates in USD per million tokens (1 credit = $0.01). effectiveFrom is the UTC day a rate took effect: the day GitHub's usage report starts billing it where that is known, otherwise the day of the GitHub docs change that listed it; 2026-08-21 is the oldest version read, and a model's first entry also prices its earlier usage. long applies to the whole request when input + cacheRead + cacheWrite exceeds its above. uncachedInput cacheWrite bills all but three uncached input tokens at the cache-write rate when a record reports no cache writes. confirmed entries match GitHub's bills or usage report; provisional ones have not been matched yet.",
|
|
34314
|
+
entries: [
|
|
34315
|
+
{
|
|
34316
|
+
model: "gpt-6.1-sol",
|
|
34317
|
+
effectiveFrom: "2026-09-29",
|
|
34318
|
+
status: "confirmed",
|
|
34319
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34320
|
+
uncachedInput: "cacheWrite",
|
|
34321
|
+
base: {
|
|
34322
|
+
input: 2,
|
|
34323
|
+
cacheRead: 0.1,
|
|
34324
|
+
cacheWrite: 2.5,
|
|
34325
|
+
output: 10
|
|
34326
|
+
},
|
|
34327
|
+
long: {
|
|
34328
|
+
above: 272000,
|
|
34329
|
+
input: 4,
|
|
34330
|
+
cacheRead: 0.2,
|
|
34331
|
+
cacheWrite: 5,
|
|
34332
|
+
output: 15
|
|
34333
|
+
},
|
|
34334
|
+
note: "Matched GitHub's daily bills exactly for OpenCode and the Copilot CLI."
|
|
34335
|
+
},
|
|
34336
|
+
{
|
|
34337
|
+
model: "gpt-6-sol",
|
|
34338
|
+
effectiveFrom: "2026-09-22",
|
|
34339
|
+
status: "confirmed",
|
|
34340
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34341
|
+
uncachedInput: "cacheWrite",
|
|
34342
|
+
base: {
|
|
34343
|
+
input: 2,
|
|
34344
|
+
cacheRead: 0.2,
|
|
34345
|
+
cacheWrite: 2.5,
|
|
34346
|
+
output: 10
|
|
34347
|
+
},
|
|
34348
|
+
long: {
|
|
34349
|
+
above: 272000,
|
|
34350
|
+
input: 4,
|
|
34351
|
+
cacheRead: 0.4,
|
|
34352
|
+
cacheWrite: 5,
|
|
34353
|
+
output: 15
|
|
34354
|
+
}
|
|
34355
|
+
},
|
|
34356
|
+
{
|
|
34357
|
+
model: "gpt-6-astra",
|
|
34358
|
+
effectiveFrom: "2026-09-04",
|
|
34359
|
+
status: "provisional",
|
|
34360
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34361
|
+
uncachedInput: "cacheWrite",
|
|
34362
|
+
base: {
|
|
34363
|
+
input: 10,
|
|
34364
|
+
cacheRead: 1,
|
|
34365
|
+
cacheWrite: 12.5,
|
|
34366
|
+
output: 50
|
|
34367
|
+
},
|
|
34368
|
+
long: {
|
|
34369
|
+
above: 272000,
|
|
34370
|
+
input: 20,
|
|
34371
|
+
cacheRead: 2,
|
|
34372
|
+
cacheWrite: 25,
|
|
34373
|
+
output: 75
|
|
34374
|
+
}
|
|
34375
|
+
},
|
|
34376
|
+
{
|
|
34377
|
+
model: "gpt-6-luna",
|
|
34378
|
+
effectiveFrom: "2026-09-22",
|
|
34379
|
+
status: "confirmed",
|
|
34380
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34381
|
+
uncachedInput: "cacheWrite",
|
|
34382
|
+
base: {
|
|
34383
|
+
input: 0.1,
|
|
34384
|
+
cacheRead: 0.01,
|
|
34385
|
+
cacheWrite: 0.125,
|
|
34386
|
+
output: 0.5
|
|
34387
|
+
},
|
|
34388
|
+
long: {
|
|
34389
|
+
above: 272000,
|
|
34390
|
+
input: 0.2,
|
|
34391
|
+
cacheRead: 0.02,
|
|
34392
|
+
cacheWrite: 0.25,
|
|
34393
|
+
output: 0.75
|
|
34394
|
+
}
|
|
34395
|
+
},
|
|
34396
|
+
{
|
|
34397
|
+
model: "gpt-5.6-sol",
|
|
34398
|
+
effectiveFrom: "2026-08-21",
|
|
34399
|
+
status: "provisional",
|
|
34400
|
+
source: "https://github.com/github/docs/blob/1cabce7332/data/tables/copilot/models-and-pricing.yml",
|
|
34401
|
+
uncachedInput: "cacheWrite",
|
|
34402
|
+
base: {
|
|
34403
|
+
input: 2,
|
|
34404
|
+
cacheRead: 0.2,
|
|
34405
|
+
cacheWrite: 2.5,
|
|
34406
|
+
output: 10
|
|
34407
|
+
},
|
|
34408
|
+
long: {
|
|
34409
|
+
above: 272000,
|
|
34410
|
+
input: 4,
|
|
34411
|
+
cacheRead: 0.4,
|
|
34412
|
+
cacheWrite: 5,
|
|
34413
|
+
output: 15
|
|
34414
|
+
},
|
|
34415
|
+
note: "Launch promotion at 50% off, through 2026-09-03."
|
|
34416
|
+
},
|
|
34417
|
+
{
|
|
34418
|
+
model: "gpt-5.6-sol",
|
|
34419
|
+
effectiveFrom: "2026-09-04",
|
|
34420
|
+
status: "provisional",
|
|
34421
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34422
|
+
uncachedInput: "cacheWrite",
|
|
34423
|
+
base: {
|
|
34424
|
+
input: 4,
|
|
34425
|
+
cacheRead: 0.4,
|
|
34426
|
+
cacheWrite: 5,
|
|
34427
|
+
output: 20
|
|
34428
|
+
},
|
|
34429
|
+
long: {
|
|
34430
|
+
above: 272000,
|
|
34431
|
+
input: 8,
|
|
34432
|
+
cacheRead: 0.8,
|
|
34433
|
+
cacheWrite: 10,
|
|
34434
|
+
output: 30
|
|
34435
|
+
}
|
|
34436
|
+
},
|
|
34437
|
+
{
|
|
34438
|
+
model: "gpt-5.6-terra",
|
|
34439
|
+
effectiveFrom: "2026-08-21",
|
|
34440
|
+
status: "provisional",
|
|
34441
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34442
|
+
uncachedInput: "cacheWrite",
|
|
34443
|
+
base: {
|
|
34444
|
+
input: 2,
|
|
34445
|
+
cacheRead: 0.2,
|
|
34446
|
+
cacheWrite: 2.5,
|
|
34447
|
+
output: 12
|
|
34448
|
+
},
|
|
34449
|
+
long: {
|
|
34450
|
+
above: 272000,
|
|
34451
|
+
input: 4,
|
|
34452
|
+
cacheRead: 0.4,
|
|
34453
|
+
cacheWrite: 5,
|
|
34454
|
+
output: 18
|
|
34455
|
+
}
|
|
34456
|
+
},
|
|
34457
|
+
{
|
|
34458
|
+
model: "gpt-5.6-luna",
|
|
34459
|
+
effectiveFrom: "2026-08-21",
|
|
34460
|
+
status: "provisional",
|
|
34461
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34462
|
+
uncachedInput: "cacheWrite",
|
|
34463
|
+
base: {
|
|
34464
|
+
input: 0.2,
|
|
34465
|
+
cacheRead: 0.02,
|
|
34466
|
+
cacheWrite: 0.25,
|
|
34467
|
+
output: 1.2
|
|
34468
|
+
},
|
|
34469
|
+
long: {
|
|
34470
|
+
above: 200000,
|
|
34471
|
+
input: 0.4,
|
|
34472
|
+
cacheRead: 0.04,
|
|
34473
|
+
cacheWrite: 0.5,
|
|
34474
|
+
output: 1.8
|
|
34475
|
+
},
|
|
34476
|
+
note: "Copilot's long-context threshold is 200K, OpenAI's 272K."
|
|
34477
|
+
},
|
|
34478
|
+
{
|
|
34479
|
+
model: "gpt-5.5",
|
|
34480
|
+
effectiveFrom: "2026-08-21",
|
|
34481
|
+
status: "confirmed",
|
|
34482
|
+
source: "https://github.com/github/docs/blob/9245795993/data/tables/copilot/models-and-pricing.yml",
|
|
34483
|
+
uncachedInput: "input",
|
|
34484
|
+
base: {
|
|
34485
|
+
input: 5,
|
|
34486
|
+
cacheRead: 0.5,
|
|
34487
|
+
cacheWrite: null,
|
|
34488
|
+
output: 30
|
|
34489
|
+
},
|
|
34490
|
+
long: {
|
|
34491
|
+
above: 272000,
|
|
34492
|
+
input: 10,
|
|
34493
|
+
cacheRead: 1,
|
|
34494
|
+
cacheWrite: null,
|
|
34495
|
+
output: 45
|
|
34496
|
+
},
|
|
34497
|
+
note: "Retired on 2026-10-19."
|
|
34498
|
+
},
|
|
34499
|
+
{
|
|
34500
|
+
model: "gpt-5.4",
|
|
34501
|
+
effectiveFrom: "2026-08-21",
|
|
34502
|
+
status: "confirmed",
|
|
34503
|
+
source: "https://github.com/github/docs/blob/9245795993/data/tables/copilot/models-and-pricing.yml",
|
|
34504
|
+
uncachedInput: "input",
|
|
34505
|
+
base: {
|
|
34506
|
+
input: 2.5,
|
|
34507
|
+
cacheRead: 0.25,
|
|
34508
|
+
cacheWrite: null,
|
|
34509
|
+
output: 15
|
|
34510
|
+
},
|
|
34511
|
+
long: {
|
|
34512
|
+
above: 272000,
|
|
34513
|
+
input: 5,
|
|
34514
|
+
cacheRead: 0.5,
|
|
34515
|
+
cacheWrite: null,
|
|
34516
|
+
output: 22.5
|
|
34517
|
+
},
|
|
34518
|
+
note: "Retired on 2026-10-19."
|
|
34519
|
+
},
|
|
34520
|
+
{
|
|
34521
|
+
model: "gpt-5.3-codex",
|
|
34522
|
+
effectiveFrom: "2026-08-21",
|
|
34523
|
+
status: "confirmed",
|
|
34524
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34525
|
+
uncachedInput: "input",
|
|
34526
|
+
base: {
|
|
34527
|
+
input: 1.75,
|
|
34528
|
+
cacheRead: 0.175,
|
|
34529
|
+
cacheWrite: null,
|
|
34530
|
+
output: 14
|
|
34531
|
+
},
|
|
34532
|
+
note: "No cache-write rate; matched GitHub's daily bills exactly at the input rate."
|
|
34533
|
+
},
|
|
34534
|
+
{
|
|
34535
|
+
model: "gpt-5.2",
|
|
34536
|
+
effectiveFrom: "2026-08-21",
|
|
34537
|
+
status: "confirmed",
|
|
34538
|
+
source: "https://developers.openai.com/api/docs/pricing",
|
|
34539
|
+
uncachedInput: "input",
|
|
34540
|
+
base: {
|
|
34541
|
+
input: 1.75,
|
|
34542
|
+
cacheRead: 0.175,
|
|
34543
|
+
cacheWrite: null,
|
|
34544
|
+
output: 14
|
|
34545
|
+
},
|
|
34546
|
+
note: "Not in GitHub's price table; its usage report bills OpenAI's list rate exactly."
|
|
34547
|
+
},
|
|
34548
|
+
{
|
|
34549
|
+
model: "gpt-5.4-mini",
|
|
34550
|
+
effectiveFrom: "2026-08-21",
|
|
34551
|
+
status: "confirmed",
|
|
34552
|
+
source: "https://github.com/github/docs/blob/9245795993/data/tables/copilot/models-and-pricing.yml",
|
|
34553
|
+
uncachedInput: "input",
|
|
34554
|
+
base: {
|
|
34555
|
+
input: 0.75,
|
|
34556
|
+
cacheRead: 0.075,
|
|
34557
|
+
cacheWrite: null,
|
|
34558
|
+
output: 4.5
|
|
34559
|
+
},
|
|
34560
|
+
note: "Retired on 2026-10-19."
|
|
34561
|
+
},
|
|
34562
|
+
{
|
|
34563
|
+
model: "claude-opus-5.5",
|
|
34564
|
+
effectiveFrom: "2026-09-22",
|
|
34565
|
+
status: "provisional",
|
|
34566
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34567
|
+
uncachedInput: "cacheWrite",
|
|
34568
|
+
base: {
|
|
34569
|
+
input: 4,
|
|
34570
|
+
cacheRead: 0.2,
|
|
34571
|
+
cacheWrite: 5,
|
|
34572
|
+
output: 20
|
|
34573
|
+
}
|
|
34574
|
+
},
|
|
34575
|
+
{
|
|
34576
|
+
model: "claude-opus-5",
|
|
34577
|
+
effectiveFrom: "2026-08-21",
|
|
34578
|
+
status: "provisional",
|
|
34579
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34580
|
+
uncachedInput: "cacheWrite",
|
|
34581
|
+
base: {
|
|
34582
|
+
input: 5,
|
|
34583
|
+
cacheRead: 0.5,
|
|
34584
|
+
cacheWrite: 6.25,
|
|
34585
|
+
output: 25
|
|
34586
|
+
}
|
|
34587
|
+
},
|
|
34588
|
+
{
|
|
34589
|
+
model: "claude-opus-4.8",
|
|
34590
|
+
effectiveFrom: "2026-08-21",
|
|
34591
|
+
status: "provisional",
|
|
34592
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34593
|
+
uncachedInput: "cacheWrite",
|
|
34594
|
+
base: {
|
|
34595
|
+
input: 5,
|
|
34596
|
+
cacheRead: 0.5,
|
|
34597
|
+
cacheWrite: 6.25,
|
|
34598
|
+
output: 25
|
|
34599
|
+
}
|
|
34600
|
+
},
|
|
34601
|
+
{
|
|
34602
|
+
model: "claude-sonnet-5.5",
|
|
34603
|
+
effectiveFrom: "2026-09-28",
|
|
34604
|
+
status: "confirmed",
|
|
34605
|
+
source: "https://github.com/github/docs/blob/9fdc6fbf59/data/tables/copilot/models-and-pricing.yml",
|
|
34606
|
+
uncachedInput: "cacheWrite",
|
|
34607
|
+
base: {
|
|
34608
|
+
input: 2,
|
|
34609
|
+
cacheRead: 0.2,
|
|
34610
|
+
cacheWrite: 2.5,
|
|
34611
|
+
output: 10
|
|
34612
|
+
},
|
|
34613
|
+
note: "GitHub's usage report bills this $0.20 cached rate through 2026-10-07, and bills uncached input as cache writes when a client reports none."
|
|
34614
|
+
},
|
|
34615
|
+
{
|
|
34616
|
+
model: "claude-sonnet-5.5",
|
|
34617
|
+
effectiveFrom: "2026-10-08",
|
|
34618
|
+
status: "confirmed",
|
|
34619
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34620
|
+
uncachedInput: "cacheWrite",
|
|
34621
|
+
base: {
|
|
34622
|
+
input: 2,
|
|
34623
|
+
cacheRead: 0.1,
|
|
34624
|
+
cacheWrite: 2.5,
|
|
34625
|
+
output: 10
|
|
34626
|
+
},
|
|
34627
|
+
note: "GitHub's docs listed the $0.10 cached rate on 2026-10-07, but its usage report bills that day at $0.20 and this rate from 2026-10-08."
|
|
34628
|
+
},
|
|
34629
|
+
{
|
|
34630
|
+
model: "claude-haiku-5.5",
|
|
34631
|
+
effectiveFrom: "2026-10-07",
|
|
34632
|
+
status: "confirmed",
|
|
34633
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34634
|
+
uncachedInput: "cacheWrite",
|
|
34635
|
+
base: {
|
|
34636
|
+
input: 0.1,
|
|
34637
|
+
cacheRead: 0.01,
|
|
34638
|
+
cacheWrite: 0.125,
|
|
34639
|
+
output: 0.5
|
|
34640
|
+
},
|
|
34641
|
+
long: {
|
|
34642
|
+
above: 1e5,
|
|
34643
|
+
input: 0.5,
|
|
34644
|
+
cacheRead: 0.05,
|
|
34645
|
+
cacheWrite: 0.625,
|
|
34646
|
+
output: 2.5
|
|
34647
|
+
}
|
|
34648
|
+
},
|
|
34649
|
+
{
|
|
34650
|
+
model: "mai-code-1.1-flash",
|
|
34651
|
+
effectiveFrom: "2026-08-21",
|
|
34652
|
+
status: "confirmed",
|
|
34653
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34654
|
+
uncachedInput: "input",
|
|
34655
|
+
base: {
|
|
34656
|
+
input: 0.2,
|
|
34657
|
+
cacheRead: 0.02,
|
|
34658
|
+
cacheWrite: null,
|
|
34659
|
+
output: 1.2
|
|
34660
|
+
}
|
|
34661
|
+
},
|
|
34662
|
+
{
|
|
34663
|
+
model: "copilot-nes-*",
|
|
34664
|
+
effectiveFrom: "2026-08-21",
|
|
34665
|
+
status: "confirmed",
|
|
34666
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34667
|
+
free: true,
|
|
34668
|
+
note: "Code completions and next edit suggestions are not billed in AI credits."
|
|
34669
|
+
},
|
|
34670
|
+
{
|
|
34671
|
+
model: "nes-*",
|
|
34672
|
+
effectiveFrom: "2026-08-21",
|
|
34673
|
+
status: "confirmed",
|
|
34674
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34675
|
+
free: true,
|
|
34676
|
+
note: "Code completions and next edit suggestions are not billed in AI credits."
|
|
34677
|
+
},
|
|
34678
|
+
{
|
|
34679
|
+
model: "gpt-4o-mini",
|
|
34680
|
+
effectiveFrom: "2026-08-21",
|
|
34681
|
+
status: "confirmed",
|
|
34682
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34683
|
+
free: true,
|
|
34684
|
+
note: "The name VS Code requests its helper model by, which Copilot records when no response model is exported."
|
|
34685
|
+
},
|
|
34686
|
+
{
|
|
34687
|
+
model: "gpt-4o-mini-*",
|
|
34688
|
+
effectiveFrom: "2026-08-21",
|
|
34689
|
+
status: "confirmed",
|
|
34690
|
+
source: "https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing",
|
|
34691
|
+
free: true,
|
|
34692
|
+
note: "VS Code's helper model: not on the rate card, and GitHub billed none of its recorded October 2026 requests."
|
|
34693
|
+
}
|
|
34694
|
+
]
|
|
34695
|
+
};
|
|
34696
|
+
|
|
34697
|
+
// packages/core/src/copilot-rates.ts
|
|
34698
|
+
var CopilotModel = exports_Schema.String.check(exports_Schema.isPattern(/^[a-z0-9][a-z0-9.-]*(-\*)?$/));
|
|
34699
|
+
var entryFields = {
|
|
34700
|
+
model: CopilotModel,
|
|
34701
|
+
effectiveFrom: Day,
|
|
34702
|
+
status: exports_Schema.Literals(["confirmed", "provisional"]),
|
|
34703
|
+
source: exports_Schema.String.check(exports_Schema.isPattern(/^https:\/\/\S+$/)),
|
|
34704
|
+
note: exports_Schema.optionalKey(exports_Schema.NonEmptyString)
|
|
34705
|
+
};
|
|
34706
|
+
var PricedEntry = exports_Schema.Struct({
|
|
34707
|
+
...entryFields,
|
|
34708
|
+
free: exports_Schema.optionalKey(exports_Schema.Literal(false)),
|
|
34709
|
+
uncachedInput: UncachedInput,
|
|
34710
|
+
base: Rates,
|
|
34711
|
+
long: exports_Schema.optionalKey(PriceTier)
|
|
34712
|
+
}).check(exports_Schema.makeFilter((entry) => entry.uncachedInput === "input" || entry.base.cacheWrite !== null && (entry.long === undefined || entry.long.cacheWrite !== null), { expected: "a cache-write rate in every tier that bills uncached input at it" }));
|
|
34713
|
+
var FreeEntry = exports_Schema.Struct({ ...entryFields, free: exports_Schema.Literal(true) });
|
|
34714
|
+
var CopilotRate = exports_Schema.Union([FreeEntry, PricedEntry]);
|
|
34715
|
+
var CopilotRateCard = exports_Schema.Struct({
|
|
34716
|
+
version: Day,
|
|
34717
|
+
description: exports_Schema.String,
|
|
34718
|
+
entries: exports_Schema.Array(CopilotRate).check(exports_Schema.isMinLength(1))
|
|
34719
|
+
}).check(exports_Schema.makeFilter((rates) => new Set(rates.entries.map((entry) => `${entry.model} ${entry.effectiveFrom}`)).size === rates.entries.length, { expected: "one entry per model and day" }));
|
|
34720
|
+
var copilotRates = exports_Schema.decodeUnknownSync(CopilotRateCard, {
|
|
34721
|
+
onExcessProperty: "error"
|
|
34722
|
+
})(copilot_rates_default);
|
|
34723
|
+
var free = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
34724
|
+
function copilotPrice(rates, model, timestamp) {
|
|
34725
|
+
const exact = rates.entries.filter((entry2) => entry2.model === model);
|
|
34726
|
+
const family = rates.entries.filter((entry2) => entry2.model.endsWith("-*") && model.startsWith(entry2.model.slice(0, -1))).toSorted((a, b) => b.model.length - a.model.length);
|
|
34727
|
+
const named = exact.length > 0 ? exact : family.filter((entry2) => entry2.model === family[0]?.model);
|
|
34728
|
+
const dated = named.toSorted((a, b) => a.effectiveFrom.localeCompare(b.effectiveFrom));
|
|
34729
|
+
const day = Number.isFinite(timestamp) ? new Date(timestamp).toISOString().slice(0, 10) : null;
|
|
34730
|
+
const entry = dated.findLast((candidate) => day === null || candidate.effectiveFrom <= day) ?? dated[0];
|
|
34731
|
+
if (entry === undefined)
|
|
34732
|
+
return;
|
|
34733
|
+
if (entry.free === true)
|
|
34734
|
+
return free;
|
|
34735
|
+
return {
|
|
34736
|
+
...entry.base,
|
|
34737
|
+
tiers: entry.long === undefined ? [] : [entry.long],
|
|
34738
|
+
uncachedInput: entry.uncachedInput
|
|
34739
|
+
};
|
|
34740
|
+
}
|
|
34741
|
+
|
|
34292
34742
|
// packages/core/src/pricing.ts
|
|
34293
34743
|
var ratesUrl = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
|
|
34744
|
+
var PerToken = exports_Schema.optionalKey(exports_Schema.Number);
|
|
34294
34745
|
var RawPrice = exports_Schema.Struct({
|
|
34295
|
-
|
|
34296
|
-
|
|
34297
|
-
|
|
34298
|
-
|
|
34299
|
-
|
|
34746
|
+
litellm_provider: exports_Schema.optionalKey(exports_Schema.String),
|
|
34747
|
+
input_cost_per_token: PerToken,
|
|
34748
|
+
output_cost_per_token: PerToken,
|
|
34749
|
+
cache_read_input_token_cost: PerToken,
|
|
34750
|
+
cache_creation_input_token_cost: PerToken,
|
|
34751
|
+
cache_creation_input_token_cost_above_1hr: PerToken,
|
|
34752
|
+
input_cost_per_token_above_100k_tokens: PerToken,
|
|
34753
|
+
output_cost_per_token_above_100k_tokens: PerToken,
|
|
34754
|
+
cache_read_input_token_cost_above_100k_tokens: PerToken,
|
|
34755
|
+
cache_creation_input_token_cost_above_100k_tokens: PerToken,
|
|
34756
|
+
cache_creation_input_token_cost_above_1hr_above_100k_tokens: PerToken,
|
|
34757
|
+
input_cost_per_token_above_128k_tokens: PerToken,
|
|
34758
|
+
output_cost_per_token_above_128k_tokens: PerToken,
|
|
34759
|
+
cache_read_input_token_cost_above_128k_tokens: PerToken,
|
|
34760
|
+
cache_creation_input_token_cost_above_128k_tokens: PerToken,
|
|
34761
|
+
cache_creation_input_token_cost_above_1hr_above_128k_tokens: PerToken,
|
|
34762
|
+
input_cost_per_token_above_200k_tokens: PerToken,
|
|
34763
|
+
output_cost_per_token_above_200k_tokens: PerToken,
|
|
34764
|
+
cache_read_input_token_cost_above_200k_tokens: PerToken,
|
|
34765
|
+
cache_creation_input_token_cost_above_200k_tokens: PerToken,
|
|
34766
|
+
cache_creation_input_token_cost_above_1hr_above_200k_tokens: PerToken,
|
|
34767
|
+
input_cost_per_token_above_272k_tokens: PerToken,
|
|
34768
|
+
output_cost_per_token_above_272k_tokens: PerToken,
|
|
34769
|
+
cache_read_input_token_cost_above_272k_tokens: PerToken,
|
|
34770
|
+
cache_creation_input_token_cost_above_272k_tokens: PerToken,
|
|
34771
|
+
cache_creation_input_token_cost_above_1hr_above_272k_tokens: PerToken,
|
|
34772
|
+
input_cost_per_token_above_512k_tokens: PerToken,
|
|
34773
|
+
output_cost_per_token_above_512k_tokens: PerToken,
|
|
34774
|
+
cache_read_input_token_cost_above_512k_tokens: PerToken,
|
|
34775
|
+
cache_creation_input_token_cost_above_512k_tokens: PerToken,
|
|
34776
|
+
cache_creation_input_token_cost_above_1hr_above_512k_tokens: PerToken
|
|
34777
|
+
});
|
|
34778
|
+
var tierFields = [
|
|
34779
|
+
{
|
|
34780
|
+
above: 1e5,
|
|
34781
|
+
input: "input_cost_per_token_above_100k_tokens",
|
|
34782
|
+
output: "output_cost_per_token_above_100k_tokens",
|
|
34783
|
+
cacheRead: "cache_read_input_token_cost_above_100k_tokens",
|
|
34784
|
+
cacheWrite: "cache_creation_input_token_cost_above_100k_tokens",
|
|
34785
|
+
cacheWrite1h: "cache_creation_input_token_cost_above_1hr_above_100k_tokens"
|
|
34786
|
+
},
|
|
34787
|
+
{
|
|
34788
|
+
above: 128000,
|
|
34789
|
+
input: "input_cost_per_token_above_128k_tokens",
|
|
34790
|
+
output: "output_cost_per_token_above_128k_tokens",
|
|
34791
|
+
cacheRead: "cache_read_input_token_cost_above_128k_tokens",
|
|
34792
|
+
cacheWrite: "cache_creation_input_token_cost_above_128k_tokens",
|
|
34793
|
+
cacheWrite1h: "cache_creation_input_token_cost_above_1hr_above_128k_tokens"
|
|
34794
|
+
},
|
|
34795
|
+
{
|
|
34796
|
+
above: 200000,
|
|
34797
|
+
input: "input_cost_per_token_above_200k_tokens",
|
|
34798
|
+
output: "output_cost_per_token_above_200k_tokens",
|
|
34799
|
+
cacheRead: "cache_read_input_token_cost_above_200k_tokens",
|
|
34800
|
+
cacheWrite: "cache_creation_input_token_cost_above_200k_tokens",
|
|
34801
|
+
cacheWrite1h: "cache_creation_input_token_cost_above_1hr_above_200k_tokens"
|
|
34802
|
+
},
|
|
34803
|
+
{
|
|
34804
|
+
above: 272000,
|
|
34805
|
+
input: "input_cost_per_token_above_272k_tokens",
|
|
34806
|
+
output: "output_cost_per_token_above_272k_tokens",
|
|
34807
|
+
cacheRead: "cache_read_input_token_cost_above_272k_tokens",
|
|
34808
|
+
cacheWrite: "cache_creation_input_token_cost_above_272k_tokens",
|
|
34809
|
+
cacheWrite1h: "cache_creation_input_token_cost_above_1hr_above_272k_tokens"
|
|
34810
|
+
},
|
|
34811
|
+
{
|
|
34812
|
+
above: 512000,
|
|
34813
|
+
input: "input_cost_per_token_above_512k_tokens",
|
|
34814
|
+
output: "output_cost_per_token_above_512k_tokens",
|
|
34815
|
+
cacheRead: "cache_read_input_token_cost_above_512k_tokens",
|
|
34816
|
+
cacheWrite: "cache_creation_input_token_cost_above_512k_tokens",
|
|
34817
|
+
cacheWrite1h: "cache_creation_input_token_cost_above_1hr_above_512k_tokens"
|
|
34818
|
+
}
|
|
34819
|
+
];
|
|
34300
34820
|
var decodeEntry = exports_Schema.decodeUnknownOption(RawPrice);
|
|
34301
34821
|
var decodePrice = exports_Schema.decodeUnknownOption(ModelPrice);
|
|
34302
34822
|
var decodeBook = exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(PriceBook));
|
|
34303
|
-
function
|
|
34304
|
-
|
|
34823
|
+
function perMillion(rate) {
|
|
34824
|
+
return rate * 1e6;
|
|
34825
|
+
}
|
|
34826
|
+
function vendorPrice(raw2) {
|
|
34827
|
+
if (raw2.input_cost_per_token === undefined || raw2.output_cost_per_token === undefined)
|
|
34305
34828
|
return null;
|
|
34306
|
-
|
|
34829
|
+
const cacheRead = raw2.cache_read_input_token_cost === undefined ? null : perMillion(raw2.cache_read_input_token_cost);
|
|
34830
|
+
const cacheWrite = raw2.cache_creation_input_token_cost === undefined ? null : perMillion(raw2.cache_creation_input_token_cost);
|
|
34831
|
+
const tiers = tierFields.flatMap((fields) => {
|
|
34832
|
+
const input = raw2[fields.input];
|
|
34833
|
+
const output = raw2[fields.output];
|
|
34834
|
+
if (input === undefined || output === undefined)
|
|
34835
|
+
return [];
|
|
34836
|
+
const read2 = raw2[fields.cacheRead];
|
|
34837
|
+
const write2 = raw2[fields.cacheWrite];
|
|
34838
|
+
const oneHour2 = raw2[fields.cacheWrite1h];
|
|
34839
|
+
const tier = {
|
|
34840
|
+
above: fields.above,
|
|
34841
|
+
input: perMillion(input),
|
|
34842
|
+
output: perMillion(output),
|
|
34843
|
+
cacheRead: read2 === undefined ? cacheRead : perMillion(read2),
|
|
34844
|
+
cacheWrite: write2 === undefined ? cacheWrite : perMillion(write2)
|
|
34845
|
+
};
|
|
34846
|
+
return [oneHour2 === undefined ? tier : { ...tier, cacheWrite1h: perMillion(oneHour2) }];
|
|
34847
|
+
});
|
|
34848
|
+
const implicitWrites = cacheWrite !== null && (raw2.litellm_provider === "openai" || raw2.litellm_provider === "github_copilot");
|
|
34849
|
+
const base = {
|
|
34850
|
+
input: perMillion(raw2.input_cost_per_token),
|
|
34851
|
+
output: perMillion(raw2.output_cost_per_token),
|
|
34852
|
+
cacheRead,
|
|
34853
|
+
cacheWrite,
|
|
34854
|
+
tiers
|
|
34855
|
+
};
|
|
34856
|
+
const oneHour = raw2.cache_creation_input_token_cost_above_1hr;
|
|
34857
|
+
const priced = oneHour === undefined ? base : { ...base, cacheWrite1h: perMillion(oneHour) };
|
|
34858
|
+
return exports_Option.getOrNull(decodePrice(implicitWrites ? { ...priced, uncachedInput: "cacheWrite" } : priced));
|
|
34307
34859
|
}
|
|
34308
34860
|
function addUsage(previous, tokens, cost) {
|
|
34309
34861
|
const pricedCostUsd = (previous?.pricedCostUsd ?? 0) + (cost ?? 0);
|
|
@@ -34322,8 +34874,14 @@ var loadPrices = exports_Effect.fn("Pricing.load")(function* (cachePath, offline
|
|
|
34322
34874
|
const now3 = yield* exports_Clock.currentTimeMillis;
|
|
34323
34875
|
const cached3 = yield* fs.readFileString(cachePath).pipe(exports_Effect.flatMap(decodeBook), exports_Effect.option);
|
|
34324
34876
|
const previous = exports_Option.getOrNull(cached3);
|
|
34325
|
-
|
|
34326
|
-
|
|
34877
|
+
const reused = previous === null ? null : PriceBook.make({
|
|
34878
|
+
status: "cached",
|
|
34879
|
+
fetchedAt: previous.fetchedAt,
|
|
34880
|
+
source: previous.source,
|
|
34881
|
+
prices: previous.prices
|
|
34882
|
+
});
|
|
34883
|
+
if (reused !== null && (offline || reused.fetchedAt !== null && now3 - Date.parse(reused.fetchedAt) < 86400000)) {
|
|
34884
|
+
return reused;
|
|
34327
34885
|
}
|
|
34328
34886
|
const unavailable = PriceBook.make({
|
|
34329
34887
|
status: "unavailable",
|
|
@@ -34340,14 +34898,7 @@ var loadPrices = exports_Effect.fn("Pricing.load")(function* (cachePath, offline
|
|
|
34340
34898
|
const prices = {};
|
|
34341
34899
|
for (const [model, entry] of Object.entries(entries3)) {
|
|
34342
34900
|
const decoded = exports_Option.getOrNull(decodeEntry(entry));
|
|
34343
|
-
|
|
34344
|
-
continue;
|
|
34345
|
-
const price = exports_Option.getOrNull(decodePrice({
|
|
34346
|
-
input: decoded.input_cost_per_token * 1e6,
|
|
34347
|
-
output: decoded.output_cost_per_token * 1e6,
|
|
34348
|
-
cacheRead: decoded.cache_read_input_token_cost === undefined ? null : decoded.cache_read_input_token_cost * 1e6,
|
|
34349
|
-
cacheWrite: decoded.cache_creation_input_token_cost === undefined ? null : decoded.cache_creation_input_token_cost * 1e6
|
|
34350
|
-
}));
|
|
34901
|
+
const price = decoded === null ? null : vendorPrice(decoded);
|
|
34351
34902
|
if (price !== null)
|
|
34352
34903
|
Object.defineProperty(prices, model, { value: price, enumerable: true });
|
|
34353
34904
|
}
|
|
@@ -34359,7 +34910,7 @@ var loadPrices = exports_Effect.fn("Pricing.load")(function* (cachePath, offline
|
|
|
34359
34910
|
});
|
|
34360
34911
|
}).pipe(exports_Effect.timeout("15 seconds"), exports_Effect.option);
|
|
34361
34912
|
if (exports_Option.isNone(fetched))
|
|
34362
|
-
return
|
|
34913
|
+
return reused ?? unavailable;
|
|
34363
34914
|
const book = fetched.value;
|
|
34364
34915
|
yield* exports_Effect.gen(function* () {
|
|
34365
34916
|
yield* fs.makeDirectory(path.dirname(cachePath), { recursive: true });
|
|
@@ -34372,13 +34923,93 @@ var loadPrices = exports_Effect.fn("Pricing.load")(function* (cachePath, offline
|
|
|
34372
34923
|
}).pipe(exports_Effect.scoped, exports_Effect.option);
|
|
34373
34924
|
return book;
|
|
34374
34925
|
});
|
|
34375
|
-
|
|
34376
|
-
|
|
34377
|
-
|
|
34378
|
-
|
|
34926
|
+
var pricingMethod = 1;
|
|
34927
|
+
function canonicalRates(rates) {
|
|
34928
|
+
return [rates.input, rates.output, rates.cacheRead, rates.cacheWrite, rates.cacheWrite1h ?? null];
|
|
34929
|
+
}
|
|
34930
|
+
function pricingBasis(vendor, overrides, rates) {
|
|
34931
|
+
if (vendor !== "fresh" && vendor !== "cached")
|
|
34932
|
+
return;
|
|
34933
|
+
const configured = Object.entries(overrides ?? {}).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([model, price]) => [
|
|
34934
|
+
model,
|
|
34935
|
+
...canonicalRates(price),
|
|
34936
|
+
price.uncachedInput ?? "input",
|
|
34937
|
+
(price.tiers ?? []).toSorted((a, b) => a.above - b.above).map((tier) => [tier.above, ...canonicalRates(tier)])
|
|
34938
|
+
]);
|
|
34939
|
+
const basis = `token-ledger-pricing@${pricingMethod};copilot-rates@${rates.version};litellm@tiers`;
|
|
34940
|
+
if (configured.length === 0)
|
|
34941
|
+
return basis;
|
|
34942
|
+
const digest2 = createHash2("sha256").update(JSON.stringify(configured)).digest("hex");
|
|
34943
|
+
return `${basis};overrides@${digest2.slice(0, 16)}`;
|
|
34944
|
+
}
|
|
34945
|
+
function configuredPricing(vendor, overrides) {
|
|
34946
|
+
const basis = pricingBasis(vendor.status, overrides, copilotRates);
|
|
34947
|
+
const source = `${vendor.source}; GitHub Copilot rates ${copilotRates.version}`;
|
|
34948
|
+
const book = {
|
|
34949
|
+
status: overrides === undefined ? vendor.status : "custom",
|
|
34950
|
+
fetchedAt: vendor.fetchedAt,
|
|
34951
|
+
source: overrides === undefined ? source : `${source}; configuration overrides`,
|
|
34952
|
+
prices: overrides === undefined ? vendor.prices : { ...vendor.prices, ...overrides }
|
|
34953
|
+
};
|
|
34954
|
+
return PriceBook.make(basis === undefined ? book : { ...book, basis });
|
|
34955
|
+
}
|
|
34956
|
+
function copilotPaid(record3) {
|
|
34957
|
+
return record3.billingProvider === undefined ? record3.provider === "copilot" : record3.billingProvider === "copilot";
|
|
34958
|
+
}
|
|
34959
|
+
function withoutVariant(model) {
|
|
34960
|
+
return model.replace(/\[1m\]$/i, "");
|
|
34961
|
+
}
|
|
34962
|
+
function vendorLookup(book, model) {
|
|
34963
|
+
const bare = withoutVariant(model);
|
|
34964
|
+
const hyphenated = bare.startsWith("claude-") ? bare.replace(/(\d)\.(?=\d)/g, "$1-") : bare;
|
|
34965
|
+
for (const name of new Set([model, bare, hyphenated])) {
|
|
34966
|
+
for (const key of [name, `openai/${name}`, `anthropic/${name}`, `xai/${name}`]) {
|
|
34967
|
+
if (Object.hasOwn(book.prices, key))
|
|
34968
|
+
return book.prices[key];
|
|
34969
|
+
}
|
|
34379
34970
|
}
|
|
34380
34971
|
return;
|
|
34381
34972
|
}
|
|
34973
|
+
function resolve6(record3, vendor) {
|
|
34974
|
+
if (!copilotPaid(record3))
|
|
34975
|
+
return vendorLookup(vendor, record3.model);
|
|
34976
|
+
const bare = withoutVariant(record3.model);
|
|
34977
|
+
const fallback = `github_copilot/${bare}`;
|
|
34978
|
+
return copilotPrice(copilotRates, bare, record3.timestamp) ?? (Object.hasOwn(vendor.prices, fallback) ? vendor.prices[fallback] : undefined) ?? vendorLookup(vendor, record3.model);
|
|
34979
|
+
}
|
|
34980
|
+
function tierFor(price, context3) {
|
|
34981
|
+
let rates = price;
|
|
34982
|
+
let above = 0;
|
|
34983
|
+
for (const tier of price.tiers ?? []) {
|
|
34984
|
+
if (tier.above < context3 && tier.above > above) {
|
|
34985
|
+
rates = tier;
|
|
34986
|
+
above = tier.above;
|
|
34987
|
+
}
|
|
34988
|
+
}
|
|
34989
|
+
return rates;
|
|
34990
|
+
}
|
|
34991
|
+
function baseRates(price) {
|
|
34992
|
+
const { input, output, cacheRead, cacheWrite } = price;
|
|
34993
|
+
return price.cacheWrite1h === undefined ? { input, output, cacheRead, cacheWrite } : { input, output, cacheRead, cacheWrite, cacheWrite1h: price.cacheWrite1h };
|
|
34994
|
+
}
|
|
34995
|
+
function priceRecord(record3, vendor) {
|
|
34996
|
+
const price = resolve6(record3, vendor);
|
|
34997
|
+
if (price === undefined)
|
|
34998
|
+
return { usd: null, base: null };
|
|
34999
|
+
const { input, cacheRead, cacheWrite, output } = record3.tokens;
|
|
35000
|
+
const rates = tierFor(price, record3.aggregate === true ? 0 : input + cacheRead + cacheWrite);
|
|
35001
|
+
const base = baseRates(price);
|
|
35002
|
+
if (cacheRead > 0 && rates.cacheRead === null || cacheWrite > 0 && rates.cacheWrite === null)
|
|
35003
|
+
return { usd: null, base };
|
|
35004
|
+
const implicitWrites = cacheWrite === 0 && price.uncachedInput === "cacheWrite";
|
|
35005
|
+
const atInput = implicitWrites ? Math.min(input, 3) : input;
|
|
35006
|
+
if (input > atInput && rates.cacheWrite === null)
|
|
35007
|
+
return { usd: null, base };
|
|
35008
|
+
const writeRate = rates.cacheWrite ?? 0;
|
|
35009
|
+
const oneHour = Math.min(record3.cacheWrite1h ?? 0, cacheWrite);
|
|
35010
|
+
const usd = (atInput * rates.input + (input - atInput) * writeRate + cacheRead * (rates.cacheRead ?? 0) + (cacheWrite - oneHour) * writeRate + oneHour * (rates.cacheWrite1h ?? writeRate) + output * rates.output) / 1e6;
|
|
35011
|
+
return { usd, base };
|
|
35012
|
+
}
|
|
34382
35013
|
|
|
34383
35014
|
// packages/core/src/projects.ts
|
|
34384
35015
|
var scpRemote = /^(?:[^/@\s]+@)?(\[[^\]\s]+\]|[^/:\\\s]+):((?!\/\/).+)$/;
|
|
@@ -34508,10 +35139,12 @@ var Assistant = exports_Schema.Struct({
|
|
|
34508
35139
|
input_tokens: exports_Schema.Natural,
|
|
34509
35140
|
output_tokens: exports_Schema.Natural,
|
|
34510
35141
|
cache_read_input_tokens: exports_Schema.optionalKey(exports_Schema.Natural),
|
|
34511
|
-
cache_creation_input_tokens: exports_Schema.optionalKey(exports_Schema.Natural)
|
|
35142
|
+
cache_creation_input_tokens: exports_Schema.optionalKey(exports_Schema.Natural),
|
|
35143
|
+
cache_creation: exports_Schema.optionalKey(exports_Schema.Unknown)
|
|
34512
35144
|
})
|
|
34513
35145
|
})
|
|
34514
35146
|
});
|
|
35147
|
+
var decodeCacheCreation = exports_Schema.decodeUnknownOption(exports_Schema.Struct({ ephemeral_1h_input_tokens: exports_Schema.optionalKey(exports_Schema.Natural) }));
|
|
34515
35148
|
function claudeParser(file2) {
|
|
34516
35149
|
return {
|
|
34517
35150
|
parse(line, lineNumber) {
|
|
@@ -34527,25 +35160,26 @@ function claudeParser(file2) {
|
|
|
34527
35160
|
const usage = event.message.usage;
|
|
34528
35161
|
const session = event.sessionId ?? file2;
|
|
34529
35162
|
const id2 = event.message.id === undefined && event.requestId === undefined ? `${file2}:${lineNumber}` : `${event.message.id ?? ""}:${event.requestId ?? ""}`;
|
|
35163
|
+
const cacheWrite = usage.cache_creation_input_tokens ?? 0;
|
|
35164
|
+
const oneHour = Math.min(exports_Option.getOrNull(decodeCacheCreation(usage.cache_creation))?.ephemeral_1h_input_tokens ?? 0, cacheWrite);
|
|
35165
|
+
const record3 = {
|
|
35166
|
+
provider: "claude",
|
|
35167
|
+
id: id2,
|
|
35168
|
+
session,
|
|
35169
|
+
timestamp: ms,
|
|
35170
|
+
model: event.message.model,
|
|
35171
|
+
cwd: event.cwd ?? null,
|
|
35172
|
+
repository: null,
|
|
35173
|
+
tokens: {
|
|
35174
|
+
input: usage.input_tokens,
|
|
35175
|
+
output: usage.output_tokens,
|
|
35176
|
+
cacheRead: usage.cache_read_input_tokens ?? 0,
|
|
35177
|
+
cacheWrite
|
|
35178
|
+
}
|
|
35179
|
+
};
|
|
34530
35180
|
return {
|
|
34531
35181
|
...empty14,
|
|
34532
|
-
records: [
|
|
34533
|
-
{
|
|
34534
|
-
provider: "claude",
|
|
34535
|
-
id: id2,
|
|
34536
|
-
session,
|
|
34537
|
-
timestamp: ms,
|
|
34538
|
-
model: event.message.model,
|
|
34539
|
-
cwd: event.cwd ?? null,
|
|
34540
|
-
repository: null,
|
|
34541
|
-
tokens: {
|
|
34542
|
-
input: usage.input_tokens,
|
|
34543
|
-
output: usage.output_tokens,
|
|
34544
|
-
cacheRead: usage.cache_read_input_tokens ?? 0,
|
|
34545
|
-
cacheWrite: usage.cache_creation_input_tokens ?? 0
|
|
34546
|
-
}
|
|
34547
|
-
}
|
|
34548
|
-
],
|
|
35182
|
+
records: [oneHour > 0 ? { ...record3, cacheWrite1h: oneHour } : record3],
|
|
34549
35183
|
warnings: event.message.id === undefined && event.requestId === undefined ? ["Some Claude records lack stable IDs; copied histories may overlap."] : []
|
|
34550
35184
|
};
|
|
34551
35185
|
}
|
|
@@ -34948,6 +35582,7 @@ function grokParser(file2) {
|
|
|
34948
35582
|
if (cacheRead + cacheWrite > count2.inputTokens)
|
|
34949
35583
|
return skipped;
|
|
34950
35584
|
records.push({
|
|
35585
|
+
aggregate: true,
|
|
34951
35586
|
provider: "grok",
|
|
34952
35587
|
id: `${session}:${promptId ?? `${file2}:${lineNumber}`}:${model}`,
|
|
34953
35588
|
session,
|
|
@@ -35206,6 +35841,7 @@ var decodeCounts = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
|
|
|
35206
35841
|
}));
|
|
35207
35842
|
var unattributedModel2 = "unknown";
|
|
35208
35843
|
var chatGptSignIn = "openai-codex";
|
|
35844
|
+
var copilotSignIn = "github-copilot";
|
|
35209
35845
|
function piParser(file2) {
|
|
35210
35846
|
let session = file2;
|
|
35211
35847
|
let cwd = null;
|
|
@@ -35248,7 +35884,7 @@ function piParser(file2) {
|
|
|
35248
35884
|
if (stamp === null || names === null || count2 === null || ms === null)
|
|
35249
35885
|
return skipped;
|
|
35250
35886
|
const model = attributed ? names.responseModel ?? names.model : undefined;
|
|
35251
|
-
const
|
|
35887
|
+
const own = {
|
|
35252
35888
|
provider: "pi",
|
|
35253
35889
|
id: stamp.id === undefined ? `${file2}:${lineNumber}` : `${stamp.id}:${stamp.timestamp}`,
|
|
35254
35890
|
session,
|
|
@@ -35258,6 +35894,7 @@ function piParser(file2) {
|
|
|
35258
35894
|
repository: null,
|
|
35259
35895
|
tokens: count2
|
|
35260
35896
|
};
|
|
35897
|
+
const record3 = attributed && names.provider === copilotSignIn && totalTokens(count2) > 0 ? { ...own, billingProvider: "copilot" } : type3 === "message" && carrier.role === "toolResult" ? { ...own, aggregate: true } : own;
|
|
35261
35898
|
const copied = forked !== null && ms < forked;
|
|
35262
35899
|
return {
|
|
35263
35900
|
...empty14,
|
|
@@ -35277,7 +35914,7 @@ function piParser(file2) {
|
|
|
35277
35914
|
}
|
|
35278
35915
|
|
|
35279
35916
|
// packages/core/src/sync.ts
|
|
35280
|
-
import { createHash as
|
|
35917
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
35281
35918
|
var hour = 3600000;
|
|
35282
35919
|
var UtcInstant = exports_Schema.String.check(exports_Schema.isPattern(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/), exports_Schema.makeFilter((s) => {
|
|
35283
35920
|
const ms = Date.parse(s);
|
|
@@ -35351,25 +35988,62 @@ var SyncPayload = exports_Schema.Struct({
|
|
|
35351
35988
|
pricing: exports_Schema.Struct({
|
|
35352
35989
|
status: PriceBook.fields.status,
|
|
35353
35990
|
fetchedAt: exports_Schema.NullOr(UtcInstant),
|
|
35354
|
-
source: Text
|
|
35991
|
+
source: Text,
|
|
35992
|
+
basis: exports_Schema.optionalKey(PricingBasis)
|
|
35355
35993
|
}),
|
|
35356
35994
|
buckets: exports_Schema.Array(SyncBucket),
|
|
35357
35995
|
coverage: exports_Schema.Array(SyncCoverage),
|
|
35358
35996
|
providerHints: exports_Schema.optionalKey(exports_Schema.Array(ProviderHint)),
|
|
35359
35997
|
snapshotAt: exports_Schema.optionalKey(UtcInstant)
|
|
35360
|
-
}).check(exports_Schema.makeFilter((payload) => (payload.version >= 2 || payload.buckets.every((bucket) => bucket.billingProvider === undefined)) && (payload.version >= 3 || !payload.buckets.some(partlyPriced)) && distinct(payload.buckets, (
|
|
35361
|
-
bucket.hourStart,
|
|
35362
|
-
bucket.sessionKey,
|
|
35363
|
-
bucket.project,
|
|
35364
|
-
bucket.provider,
|
|
35365
|
-
bucket.billingProvider ?? null,
|
|
35366
|
-
bucket.model
|
|
35367
|
-
])) && distinct(payload.coverage, (entry) => entry.provider) && distinct(payload.providerHints ?? [], (hint) => JSON.stringify([hint.provider, hint.hourStart, hint.plan])), {
|
|
35998
|
+
}).check(exports_Schema.makeFilter((payload) => (payload.version >= 2 || payload.buckets.every((bucket) => bucket.billingProvider === undefined)) && (payload.version >= 3 || !payload.buckets.some(partlyPriced)) && distinct(payload.buckets, bucketKey) && distinct(payload.coverage, (entry) => entry.provider) && distinct(payload.providerHints ?? [], (hint) => JSON.stringify([hint.provider, hint.hourStart, hint.plan])), {
|
|
35368
35999
|
expected: "unique bucket keys, coverage providers, and plan hints, and a version carrying every bucket"
|
|
35369
36000
|
}), exports_Schema.makeFilter((payload) => {
|
|
35370
36001
|
const replaced = replacedProviders(payload.coverage);
|
|
35371
36002
|
return [...payload.buckets, ...payload.providerHints ?? []].every((entry) => replaced.has(entry.provider) && entry.hourStart >= payload.window.start && entry.hourStart < payload.window.end);
|
|
35372
36003
|
}));
|
|
36004
|
+
var maxRepriceBuckets = 20000;
|
|
36005
|
+
var RepricePayload = exports_Schema.Struct({
|
|
36006
|
+
version: exports_Schema.Literal(1),
|
|
36007
|
+
clientVersion: NonEmptyText,
|
|
36008
|
+
pricing: exports_Schema.Struct({
|
|
36009
|
+
status: PriceBook.fields.status,
|
|
36010
|
+
fetchedAt: exports_Schema.NullOr(UtcInstant),
|
|
36011
|
+
source: Text,
|
|
36012
|
+
basis: PricingBasis
|
|
36013
|
+
}),
|
|
36014
|
+
buckets: exports_Schema.Array(SyncBucket).check(exports_Schema.isMaxLength(maxRepriceBuckets))
|
|
36015
|
+
}).check(exports_Schema.makeFilter((payload) => distinct(payload.buckets, bucketKey), {
|
|
36016
|
+
expected: "unique bucket keys"
|
|
36017
|
+
}));
|
|
36018
|
+
var maxRepriceBytes = 12 * 1024 * 1024;
|
|
36019
|
+
function repriceChunks(buckets) {
|
|
36020
|
+
const chunks2 = [];
|
|
36021
|
+
let chunk = [];
|
|
36022
|
+
let bytes2 = 0;
|
|
36023
|
+
for (const bucket of buckets) {
|
|
36024
|
+
const size7 = Buffer.byteLength(JSON.stringify(bucket)) + 1;
|
|
36025
|
+
if (chunk.length > 0 && (chunk.length >= maxRepriceBuckets || bytes2 + size7 > maxRepriceBytes)) {
|
|
36026
|
+
chunks2.push(chunk);
|
|
36027
|
+
chunk = [];
|
|
36028
|
+
bytes2 = 0;
|
|
36029
|
+
}
|
|
36030
|
+
chunk.push(bucket);
|
|
36031
|
+
bytes2 += size7;
|
|
36032
|
+
}
|
|
36033
|
+
if (chunk.length > 0)
|
|
36034
|
+
chunks2.push(chunk);
|
|
36035
|
+
return chunks2;
|
|
36036
|
+
}
|
|
36037
|
+
function bucketKey(bucket) {
|
|
36038
|
+
return JSON.stringify([
|
|
36039
|
+
bucket.hourStart,
|
|
36040
|
+
bucket.sessionKey,
|
|
36041
|
+
bucket.project,
|
|
36042
|
+
bucket.provider,
|
|
36043
|
+
bucket.billingProvider ?? null,
|
|
36044
|
+
bucket.model
|
|
36045
|
+
]);
|
|
36046
|
+
}
|
|
35373
36047
|
function distinct(items, key) {
|
|
35374
36048
|
return new Set(items.map(key)).size === items.length;
|
|
35375
36049
|
}
|
|
@@ -35381,7 +36055,7 @@ function hourRange(range3) {
|
|
|
35381
36055
|
};
|
|
35382
36056
|
}
|
|
35383
36057
|
function sessionKey(provider, session) {
|
|
35384
|
-
return
|
|
36058
|
+
return createHash3("sha256").update(`${provider}\x00${session}`).digest("hex").slice(0, 32);
|
|
35385
36059
|
}
|
|
35386
36060
|
function sessionBuckets(pricing) {
|
|
35387
36061
|
const totals = new Map;
|
|
@@ -35399,7 +36073,7 @@ function sessionBuckets(pricing) {
|
|
|
35399
36073
|
model
|
|
35400
36074
|
]);
|
|
35401
36075
|
const previous = totals.get(key);
|
|
35402
|
-
const cost =
|
|
36076
|
+
const cost = priceRecord(record3, pricing).usd;
|
|
35403
36077
|
totals.set(key, {
|
|
35404
36078
|
record: previous?.record ?? record3,
|
|
35405
36079
|
project,
|
|
@@ -35639,14 +36313,14 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35639
36313
|
const rows = new Map;
|
|
35640
36314
|
const coverage = yield* scan2(request3, window, window.dayOf, (record3, { project }, day) => {
|
|
35641
36315
|
const key = JSON.stringify([project, day, record3.provider, record3.model]);
|
|
35642
|
-
const
|
|
36316
|
+
const { usd, base } = priceRecord(record3, request3.pricing);
|
|
35643
36317
|
rows.set(key, {
|
|
35644
36318
|
project,
|
|
35645
36319
|
day,
|
|
35646
36320
|
provider: record3.provider,
|
|
35647
36321
|
model: record3.model,
|
|
35648
|
-
pricePerMillion:
|
|
35649
|
-
...addUsage(rows.get(key), record3.tokens,
|
|
36322
|
+
pricePerMillion: base,
|
|
36323
|
+
...addUsage(rows.get(key), record3.tokens, usd)
|
|
35650
36324
|
});
|
|
35651
36325
|
});
|
|
35652
36326
|
return UsageReport.make({
|
|
@@ -35656,11 +36330,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35656
36330
|
timeZone: request3.timeZone.id,
|
|
35657
36331
|
currency: "USD",
|
|
35658
36332
|
costBasis: "api-equivalent",
|
|
35659
|
-
pricing:
|
|
35660
|
-
status: request3.pricing.status,
|
|
35661
|
-
fetchedAt: request3.pricing.fetchedAt,
|
|
35662
|
-
source: request3.pricing.source
|
|
35663
|
-
},
|
|
36333
|
+
pricing: provenance(request3.pricing),
|
|
35664
36334
|
rows: [...rows.values()].toSorted((a, b) => a.project.localeCompare(b.project) || a.day.localeCompare(b.day) || a.provider.localeCompare(b.provider) || a.model.localeCompare(b.model)),
|
|
35665
36335
|
coverage
|
|
35666
36336
|
});
|
|
@@ -35678,7 +36348,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35678
36348
|
const snapshotAt = yield* exports_Clock.currentTimeMillis;
|
|
35679
36349
|
const coverage = yield* scan2(request3, { start: from, end: requested.end }, (timestamp2) => timestamp2 >= from && timestamp2 < requested.end ? timestamp2 : undefined, (record3, attribution, timestamp2) => {
|
|
35680
36350
|
earliest = Math.min(earliest, timestamp2);
|
|
35681
|
-
buckets.add(record3, attribution
|
|
36351
|
+
buckets.add(record3, uploadedProject(attribution));
|
|
35682
36352
|
}, (plan) => {
|
|
35683
36353
|
earliest = Math.min(earliest, plan.timestamp);
|
|
35684
36354
|
hints.add(plan);
|
|
@@ -35699,11 +36369,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35699
36369
|
},
|
|
35700
36370
|
currency: "USD",
|
|
35701
36371
|
costBasis: "api-equivalent",
|
|
35702
|
-
pricing:
|
|
35703
|
-
status: request3.pricing.status,
|
|
35704
|
-
fetchedAt: request3.pricing.fetchedAt,
|
|
35705
|
-
source: request3.pricing.source
|
|
35706
|
-
},
|
|
36372
|
+
pricing: provenance(request3.pricing),
|
|
35707
36373
|
buckets: uploadedBuckets,
|
|
35708
36374
|
coverage: summary,
|
|
35709
36375
|
providerHints: hints.finish().filter((hint) => replaced.has(hint.provider)),
|
|
@@ -35713,13 +36379,45 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35713
36379
|
})));
|
|
35714
36380
|
return { payload, since };
|
|
35715
36381
|
});
|
|
36382
|
+
const repriceBuckets = exports_Effect.fn("Ledger.repriceBuckets")(function* (input, provider, range3) {
|
|
36383
|
+
const request3 = yield* decode5(input);
|
|
36384
|
+
const hours2 = hourRange(range3);
|
|
36385
|
+
if (hours2.start !== range3.start || hours2.end !== range3.end || range3.start >= range3.end)
|
|
36386
|
+
return yield* new InvalidRequest({ message: "Expected a range of whole UTC hours." });
|
|
36387
|
+
const buckets = sessionBuckets(request3.pricing);
|
|
36388
|
+
const coverage = yield* scan2({ ...request3, sources: request3.sources.filter((source) => source.provider === provider) }, range3, (timestamp2) => timestamp2 >= range3.start && timestamp2 < range3.end ? timestamp2 : undefined, (record3, attribution) => buckets.add(record3, uploadedProject(attribution)), () => {
|
|
36389
|
+
return;
|
|
36390
|
+
});
|
|
36391
|
+
const summary = providerCoverage(coverage).find((entry) => entry.provider === provider) ?? {
|
|
36392
|
+
provider,
|
|
36393
|
+
status: "missing",
|
|
36394
|
+
files: 0,
|
|
36395
|
+
filesBeforeWindow: 0,
|
|
36396
|
+
unreadable: 0,
|
|
36397
|
+
malformedLines: 0,
|
|
36398
|
+
skippedRecords: 0,
|
|
36399
|
+
duplicates: 0
|
|
36400
|
+
};
|
|
36401
|
+
return {
|
|
36402
|
+
buckets: replacedProviders([summary]).has(provider) ? buckets.finish() : [],
|
|
36403
|
+
coverage: summary
|
|
36404
|
+
};
|
|
36405
|
+
});
|
|
35716
36406
|
return Ledger.of({
|
|
35717
36407
|
report,
|
|
35718
36408
|
syncPayload: (request3, client, onWarning) => exports_Effect.map(payloadFrom(request3, client, false, onWarning), ({ payload }) => payload),
|
|
35719
|
-
historyPayload: (request3, client, onWarning) => payloadFrom(request3, client, true, onWarning)
|
|
36409
|
+
historyPayload: (request3, client, onWarning) => payloadFrom(request3, client, true, onWarning),
|
|
36410
|
+
repriceBuckets
|
|
35720
36411
|
});
|
|
35721
36412
|
}));
|
|
35722
36413
|
}
|
|
36414
|
+
function uploadedProject(attribution) {
|
|
36415
|
+
return attribution.shareable ? attribution.project : unattributed;
|
|
36416
|
+
}
|
|
36417
|
+
function provenance(pricing) {
|
|
36418
|
+
const { status, fetchedAt, source } = pricing;
|
|
36419
|
+
return pricing.basis === undefined ? { status, fetchedAt, source } : { status, fetchedAt, source, basis: pricing.basis };
|
|
36420
|
+
}
|
|
35723
36421
|
function acceptsFile(path, source, file2) {
|
|
35724
36422
|
if (source.path === file2)
|
|
35725
36423
|
return true;
|
|
@@ -43055,7 +43753,7 @@ var runWith2 = (command, config) => {
|
|
|
43055
43753
|
// packages/cli/package.json
|
|
43056
43754
|
var package_default = {
|
|
43057
43755
|
name: "@ponbac/token-ledger",
|
|
43058
|
-
version: "0.
|
|
43756
|
+
version: "0.10.0",
|
|
43059
43757
|
private: true,
|
|
43060
43758
|
type: "module",
|
|
43061
43759
|
bin: {
|
|
@@ -44220,6 +44918,51 @@ var saveSyncSettings = exports_Effect.fn("Settings.saveSync")(function* (directo
|
|
|
44220
44918
|
}).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: `Cannot save ${file2}.` })));
|
|
44221
44919
|
return file2;
|
|
44222
44920
|
});
|
|
44921
|
+
var CompletedReprice = exports_Schema.Struct({
|
|
44922
|
+
server: exports_Schema.String,
|
|
44923
|
+
provider: Provider,
|
|
44924
|
+
basis: PricingBasis,
|
|
44925
|
+
from: exports_Schema.DateTimeUtcFromString,
|
|
44926
|
+
coveredUntil: exports_Schema.DateTimeUtcFromString
|
|
44927
|
+
});
|
|
44928
|
+
var Repricing = exports_Schema.Struct({
|
|
44929
|
+
version: exports_Schema.Literal(1),
|
|
44930
|
+
completed: exports_Schema.Array(CompletedReprice)
|
|
44931
|
+
});
|
|
44932
|
+
var loadRepricing = exports_Effect.fn("Settings.loadRepricing")(function* (directory) {
|
|
44933
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
44934
|
+
const path = yield* exports_Path.Path;
|
|
44935
|
+
return yield* fs.readFileString(path.join(directory, "repricing.json")).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(Repricing))), exports_Effect.map((repricing) => repricing.completed), exports_Effect.orElseSucceed(() => []));
|
|
44936
|
+
});
|
|
44937
|
+
var saveRepricing = exports_Effect.fn("Settings.saveRepricing")(function* (directory, completed) {
|
|
44938
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
44939
|
+
const path = yield* exports_Path.Path;
|
|
44940
|
+
const file2 = path.join(directory, "repricing.json");
|
|
44941
|
+
yield* exports_Effect.gen(function* () {
|
|
44942
|
+
const repricing = yield* exports_Schema.encodeEffect(Repricing)({ version: 1, completed });
|
|
44943
|
+
yield* fs.makeDirectory(directory, { recursive: true });
|
|
44944
|
+
const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
|
|
44945
|
+
directory,
|
|
44946
|
+
prefix: ".repricing-"
|
|
44947
|
+
});
|
|
44948
|
+
const temporary = path.join(temporaryDirectory, "repricing.json");
|
|
44949
|
+
yield* fs.writeFileString(temporary, `${JSON.stringify(repricing, null, 2)}
|
|
44950
|
+
`, { flag: "wx" });
|
|
44951
|
+
yield* fs.rename(temporary, file2);
|
|
44952
|
+
}).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: "Cannot save repricing.json in the settings directory." })));
|
|
44953
|
+
});
|
|
44954
|
+
var ScheduleSettings = exports_Schema.Struct({ version: exports_Schema.Literal(1) });
|
|
44955
|
+
var scheduleSettled = exports_Effect.fn("Settings.scheduleSettled")(function* (directory) {
|
|
44956
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
44957
|
+
const path = yield* exports_Path.Path;
|
|
44958
|
+
return yield* fs.readFileString(path.join(directory, "schedule.json")).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(ScheduleSettings))), exports_Effect.as(true), exports_Effect.orElseSucceed(() => false));
|
|
44959
|
+
});
|
|
44960
|
+
var settleSchedule = exports_Effect.fn("Settings.settleSchedule")(function* (directory) {
|
|
44961
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
44962
|
+
const path = yield* exports_Path.Path;
|
|
44963
|
+
yield* fs.makeDirectory(directory, { recursive: true }).pipe(exports_Effect.andThen(fs.writeFileString(path.join(directory, "schedule.json"), `${JSON.stringify({ version: 1 }, null, 2)}
|
|
44964
|
+
`)), exports_Effect.mapError(() => new SettingsError({ message: "Cannot save schedule.json in the settings directory." })));
|
|
44965
|
+
});
|
|
44223
44966
|
|
|
44224
44967
|
// packages/cli/src/schedule.ts
|
|
44225
44968
|
class ScheduleError extends exports_Schema.TaggedError()("ScheduleError", {
|
|
@@ -44237,6 +44980,8 @@ var intervals = [
|
|
|
44237
44980
|
["12h", 12],
|
|
44238
44981
|
["24h", 24]
|
|
44239
44982
|
];
|
|
44983
|
+
var defaultInterval = 2;
|
|
44984
|
+
var isTimeOfDay = exports_Schema.is(TimeOfDay);
|
|
44240
44985
|
function syncTimes(job) {
|
|
44241
44986
|
const hour2 = Number(job.at.slice(0, 2));
|
|
44242
44987
|
const minute = job.at.slice(3);
|
|
@@ -44248,6 +44993,11 @@ var unit = "token-ledger-sync";
|
|
|
44248
44993
|
var label = "com.github.ponbac.token-ledger.sync";
|
|
44249
44994
|
var task = "token-ledger sync";
|
|
44250
44995
|
var packageSpec = "@ponbac/token-ledger@latest";
|
|
44996
|
+
var readJob = (file2) => exports_Effect.gen(function* () {
|
|
44997
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
44998
|
+
return (yield* fs.exists(file2)) ? exports_Option.some(yield* fs.readFileString(file2)) : exports_Option.none();
|
|
44999
|
+
}).pipe(exports_Effect.mapError(() => new ScheduleError({ message: `Cannot read ${file2}.` })));
|
|
45000
|
+
var dailyAt = (hour2, minute) => exports_Option.filter(exports_Option.some(`${hour2.padStart(2, "0")}:${minute.padStart(2, "0")}`), isTimeOfDay);
|
|
44251
45001
|
function run6(outcome, program, args2, hint = "") {
|
|
44252
45002
|
return Action3.Run({
|
|
44253
45003
|
program,
|
|
@@ -44279,6 +45029,17 @@ var posixScript = (job) => [
|
|
|
44279
45029
|
].join("; ");
|
|
44280
45030
|
var posixJob = (job) => quotable(job, /\p{Cc}/u, "a control character");
|
|
44281
45031
|
var systemdQuoted = (value5) => `"${value5.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("%", "%%").replaceAll("$", () => "$$")}"`;
|
|
45032
|
+
var timerUnit = (job) => `[Unit]
|
|
45033
|
+
Description=AI usage sync ${job.every === 24 ? "once a day" : `every ${job.every}h`}
|
|
45034
|
+
|
|
45035
|
+
[Timer]
|
|
45036
|
+
OnCalendar=*-*-* ${syncTimes(job).map((time2) => time2.slice(0, 2)).join(",")}:${job.at.slice(3)}:00
|
|
45037
|
+
Persistent=true
|
|
45038
|
+
RandomizedDelaySec=10m
|
|
45039
|
+
|
|
45040
|
+
[Install]
|
|
45041
|
+
WantedBy=timers.target
|
|
45042
|
+
`;
|
|
44282
45043
|
function systemdTimer(directory) {
|
|
44283
45044
|
const service4 = `${directory}/${unit}.service`;
|
|
44284
45045
|
const timer = `${directory}/${unit}.timer`;
|
|
@@ -44297,20 +45058,7 @@ Type=oneshot
|
|
|
44297
45058
|
ExecStart=/bin/sh -lc ${systemdQuoted(posixScript(job2))}
|
|
44298
45059
|
`
|
|
44299
45060
|
}),
|
|
44300
|
-
Action3.Write({
|
|
44301
|
-
file: timer,
|
|
44302
|
-
contents: `[Unit]
|
|
44303
|
-
Description=AI usage sync ${job2.every === 24 ? "once a day" : `every ${job2.every}h`}
|
|
44304
|
-
|
|
44305
|
-
[Timer]
|
|
44306
|
-
OnCalendar=*-*-* ${syncTimes(job2).map((time2) => time2.slice(0, 2)).join(",")}:${job2.at.slice(3)}:00
|
|
44307
|
-
Persistent=true
|
|
44308
|
-
RandomizedDelaySec=10m
|
|
44309
|
-
|
|
44310
|
-
[Install]
|
|
44311
|
-
WantedBy=timers.target
|
|
44312
|
-
`
|
|
44313
|
-
}),
|
|
45061
|
+
Action3.Write({ file: timer, contents: timerUnit(job2) }),
|
|
44314
45062
|
systemctl("required", ["daemon-reload"]),
|
|
44315
45063
|
systemctl("required", ["enable", `${unit}.timer`]),
|
|
44316
45064
|
systemctl("required", ["restart", `${unit}.timer`])
|
|
@@ -44326,31 +45074,45 @@ WantedBy=timers.target
|
|
|
44326
45074
|
gone: [3, 4]
|
|
44327
45075
|
})
|
|
44328
45076
|
],
|
|
44329
|
-
status: [systemctl("reported", ["status", "--no-pager", `${unit}.timer`, `${unit}.service`])]
|
|
45077
|
+
status: [systemctl("reported", ["status", "--no-pager", `${unit}.timer`, `${unit}.service`])],
|
|
45078
|
+
dailyJob: readJob(timer).pipe(exports_Effect.map(exports_Option.flatMap((contents) => exports_Option.map(exports_Option.flatMap(exports_Option.fromNullishOr(/^OnCalendar=\*-\*-\* (\d{2}):(\d{2}):00$/m.exec(contents)), ([, hour2 = "", minute = ""]) => dailyAt(hour2, minute)), (at) => ({
|
|
45079
|
+
at,
|
|
45080
|
+
retime: (every4) => [
|
|
45081
|
+
Action3.Write({ file: timer, contents: timerUnit({ at, every: every4 }) }),
|
|
45082
|
+
systemctl("required", ["daemon-reload"]),
|
|
45083
|
+
systemctl("required", ["try-restart", `${unit}.timer`])
|
|
45084
|
+
],
|
|
45085
|
+
undo: [Action3.Write({ file: timer, contents })]
|
|
45086
|
+
})))))
|
|
44330
45087
|
};
|
|
44331
45088
|
}
|
|
44332
45089
|
var xmlText = (value5) => value5.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
45090
|
+
var calendarInterval = (job) => `<key>StartCalendarInterval</key>
|
|
45091
|
+
<array>
|
|
45092
|
+
${syncTimes(job).map((time2) => {
|
|
45093
|
+
const [hour2, minute] = time2.split(":").map(Number);
|
|
45094
|
+
return ` <dict>
|
|
45095
|
+
<key>Hour</key>
|
|
45096
|
+
<integer>${hour2}</integer>
|
|
45097
|
+
<key>Minute</key>
|
|
45098
|
+
<integer>${minute}</integer>
|
|
45099
|
+
</dict>`;
|
|
45100
|
+
}).join(`
|
|
45101
|
+
`)}
|
|
45102
|
+
</array>`;
|
|
45103
|
+
var startCalendarInterval = /<key>StartCalendarInterval<\/key>\s*(?:<dict>[\s\S]*?<\/dict>|<array>[\s\S]*?<\/array>)/;
|
|
45104
|
+
var hourAndMinute = /<key>Hour<\/key>\s*<integer>(\d{1,2})<\/integer>\s*<key>Minute<\/key>\s*<integer>(\d{1,2})<\/integer>/g;
|
|
45105
|
+
var reloadAgent = 'while kill -0 "$PPID" 2>/dev/null; do sleep 1; done; launchctl bootout "$1"; for attempt in 1 2 3 4 5; do launchctl bootstrap "$2" "$3" && break; sleep 1; done';
|
|
44333
45106
|
function launchAgent(home, uid) {
|
|
44334
45107
|
const plist = `${home}/Library/LaunchAgents/${label}.plist`;
|
|
44335
45108
|
const log3 = `${home}/Library/Logs/${unit}.log`;
|
|
44336
45109
|
const domain = `gui/${uid}`;
|
|
44337
45110
|
return {
|
|
44338
45111
|
name: "launchd agent",
|
|
44339
|
-
install: (job) => posixJob(job).pipe(exports_Effect.map((job2) =>
|
|
44340
|
-
|
|
44341
|
-
|
|
44342
|
-
|
|
44343
|
-
<key>Hour</key>
|
|
44344
|
-
<integer>${hour2}</integer>
|
|
44345
|
-
<key>Minute</key>
|
|
44346
|
-
<integer>${minute}</integer>
|
|
44347
|
-
</dict>`;
|
|
44348
|
-
}).join(`
|
|
44349
|
-
`);
|
|
44350
|
-
return [
|
|
44351
|
-
Action3.Write({
|
|
44352
|
-
file: plist,
|
|
44353
|
-
contents: `<?xml version="1.0" encoding="UTF-8"?>
|
|
45112
|
+
install: (job) => posixJob(job).pipe(exports_Effect.map((job2) => [
|
|
45113
|
+
Action3.Write({
|
|
45114
|
+
file: plist,
|
|
45115
|
+
contents: `<?xml version="1.0" encoding="UTF-8"?>
|
|
44354
45116
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
44355
45117
|
<plist version="1.0">
|
|
44356
45118
|
<dict>
|
|
@@ -44364,10 +45126,7 @@ function launchAgent(home, uid) {
|
|
|
44364
45126
|
</array>
|
|
44365
45127
|
<key>RunAtLoad</key>
|
|
44366
45128
|
<true/>
|
|
44367
|
-
|
|
44368
|
-
<array>
|
|
44369
|
-
${times}
|
|
44370
|
-
</array>
|
|
45129
|
+
${calendarInterval(job2)}
|
|
44371
45130
|
<key>StandardOutPath</key>
|
|
44372
45131
|
<string>${xmlText(log3)}</string>
|
|
44373
45132
|
<key>StandardErrorPath</key>
|
|
@@ -44375,17 +45134,35 @@ ${times}
|
|
|
44375
45134
|
</dict>
|
|
44376
45135
|
</plist>
|
|
44377
45136
|
`
|
|
44378
|
-
|
|
44379
|
-
|
|
44380
|
-
|
|
44381
|
-
|
|
44382
|
-
})),
|
|
45137
|
+
}),
|
|
45138
|
+
run6("silent", "launchctl", ["bootout", `${domain}/${label}`]),
|
|
45139
|
+
run6("required", "launchctl", ["bootstrap", domain, plist])
|
|
45140
|
+
])),
|
|
44383
45141
|
uninstall: [
|
|
44384
45142
|
run6("reported", "launchctl", ["bootout", `${domain}/${label}`]),
|
|
44385
45143
|
Action3.Remove({ file: plist }),
|
|
44386
45144
|
run6("absent", "launchctl", ["print", `${domain}/${label}`], "The agent is still loaded; launchd's reason is shown above.")
|
|
44387
45145
|
],
|
|
44388
|
-
status: [run6("reported", "launchctl", ["print", `${domain}/${label}`])]
|
|
45146
|
+
status: [run6("reported", "launchctl", ["print", `${domain}/${label}`])],
|
|
45147
|
+
dailyJob: readJob(plist).pipe(exports_Effect.map(exports_Option.flatMap((contents) => exports_Option.flatMap(exports_Option.fromNullishOr(startCalendarInterval.exec(contents)), ([block]) => {
|
|
45148
|
+
const times = [...block.matchAll(hourAndMinute)];
|
|
45149
|
+
const [, hour2 = "", minute = ""] = times[0] ?? [];
|
|
45150
|
+
return times.length === 1 ? exports_Option.map(dailyAt(hour2, minute), (at) => ({
|
|
45151
|
+
at,
|
|
45152
|
+
retime: (every4) => [
|
|
45153
|
+
Action3.Write({
|
|
45154
|
+
file: plist,
|
|
45155
|
+
contents: contents.replace(startCalendarInterval, () => calendarInterval({ at, every: every4 }))
|
|
45156
|
+
}),
|
|
45157
|
+
Action3.Launch({
|
|
45158
|
+
program: "/bin/sh",
|
|
45159
|
+
args: ["-c", reloadAgent, "sh", `${domain}/${label}`, domain, plist],
|
|
45160
|
+
shown: `/bin/sh -c '${reloadAgent}' sh ${domain}/${label} ${domain} ${plist}`
|
|
45161
|
+
})
|
|
45162
|
+
],
|
|
45163
|
+
undo: [Action3.Write({ file: plist, contents })]
|
|
45164
|
+
})) : exports_Option.none();
|
|
45165
|
+
}))))
|
|
44389
45166
|
};
|
|
44390
45167
|
}
|
|
44391
45168
|
var cmdWord = (value5) => /^[\w@+=:,./\\-]+$/.test(value5) ? value5 : `"${value5}"`;
|
|
@@ -44396,6 +45173,33 @@ var powershellArguments = (script) => [
|
|
|
44396
45173
|
Buffer.from(script, "utf16le").toString("base64")
|
|
44397
45174
|
];
|
|
44398
45175
|
var jscriptString = (value5) => JSON.stringify(value5).replaceAll(/[\u007f-\uffff]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
45176
|
+
var taskTrigger = (job) => [
|
|
45177
|
+
`$trigger = New-ScheduledTaskTrigger -Daily -At '${syncTimes(job)[0]}'`,
|
|
45178
|
+
...job.every === 24 ? [] : [
|
|
45179
|
+
`$trigger.Repetition = (New-ScheduledTaskTrigger -Once -At '${syncTimes(job)[0]}' -RepetitionInterval (New-TimeSpan -Hours ${job.every}) -RepetitionDuration (New-TimeSpan -Hours ${24 - job.every})).Repetition`
|
|
45180
|
+
]
|
|
45181
|
+
];
|
|
45182
|
+
var dailyTaskScript = [
|
|
45183
|
+
"$ErrorActionPreference = 'Stop'",
|
|
45184
|
+
`try { $task = Get-ScheduledTask -TaskName ${powershellString(task)} }`,
|
|
45185
|
+
"catch { if ($_.CategoryInfo.Category -eq 'ObjectNotFound') { exit 0 }; throw }",
|
|
45186
|
+
"if (@($task.Triggers).Count -eq 1) {",
|
|
45187
|
+
" $trigger = @($task.Triggers)[0]",
|
|
45188
|
+
" if ($trigger.CimClass.CimClassName -eq 'MSFT_TaskDailyTrigger' -and $trigger.DaysInterval -eq 1 -and -not $trigger.Repetition.Interval) {",
|
|
45189
|
+
" $trigger.StartBoundary.Substring(11, 5)",
|
|
45190
|
+
" }",
|
|
45191
|
+
"}"
|
|
45192
|
+
].join(`
|
|
45193
|
+
`);
|
|
45194
|
+
var powershell = (script) => Action3.Run({
|
|
45195
|
+
program: "powershell.exe",
|
|
45196
|
+
args: powershellArguments(script),
|
|
45197
|
+
shown: `powershell.exe ${powershellOptions.join(" ")} <the script below, as UTF-16LE Base64>
|
|
45198
|
+
${script}`,
|
|
45199
|
+
outcome: "required",
|
|
45200
|
+
hint: "",
|
|
45201
|
+
gone: []
|
|
45202
|
+
});
|
|
44399
45203
|
function taskScheduler(file2) {
|
|
44400
45204
|
return {
|
|
44401
45205
|
name: "Task Scheduler task",
|
|
@@ -44409,10 +45213,7 @@ function taskScheduler(file2) {
|
|
|
44409
45213
|
"$ErrorActionPreference = 'Stop'",
|
|
44410
45214
|
"$ProgressPreference = 'SilentlyContinue'",
|
|
44411
45215
|
`$action = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ${powershellString(`//B //Nologo //E:JScript "${file2}"`)}`,
|
|
44412
|
-
|
|
44413
|
-
...job2.every === 24 ? [] : [
|
|
44414
|
-
`$trigger.Repetition = (New-ScheduledTaskTrigger -Once -At '${syncTimes(job2)[0]}' -RepetitionInterval (New-TimeSpan -Hours ${job2.every}) -RepetitionDuration (New-TimeSpan -Hours ${24 - job2.every})).Repetition`
|
|
44415
|
-
],
|
|
45216
|
+
...taskTrigger(job2),
|
|
44416
45217
|
"$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
|
|
44417
45218
|
`Register-ScheduledTask -TaskName ${powershellString(task)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`
|
|
44418
45219
|
].join(`
|
|
@@ -44424,15 +45225,7 @@ function taskScheduler(file2) {
|
|
|
44424
45225
|
WScript.Quit(shell.Run(${jscriptString(`cmd.exe /d /v:off /s /c "${command}"`)}, 0, true));
|
|
44425
45226
|
`
|
|
44426
45227
|
}),
|
|
44427
|
-
|
|
44428
|
-
program: "powershell.exe",
|
|
44429
|
-
args: powershellArguments(script),
|
|
44430
|
-
shown: `powershell.exe ${powershellOptions.join(" ")} <the script below, as UTF-16LE Base64>
|
|
44431
|
-
${script}`,
|
|
44432
|
-
outcome: "required",
|
|
44433
|
-
hint: "",
|
|
44434
|
-
gone: []
|
|
44435
|
-
})
|
|
45228
|
+
powershell(script)
|
|
44436
45229
|
];
|
|
44437
45230
|
})),
|
|
44438
45231
|
uninstall: [
|
|
@@ -44440,7 +45233,33 @@ ${script}`,
|
|
|
44440
45233
|
run6("absent", "schtasks.exe", ["/Query", "/TN", task], "The task is still registered; Task Scheduler's reason is shown above."),
|
|
44441
45234
|
Action3.Remove({ file: file2 })
|
|
44442
45235
|
],
|
|
44443
|
-
status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])]
|
|
45236
|
+
status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])],
|
|
45237
|
+
dailyJob: exports_Effect.gen(function* () {
|
|
45238
|
+
const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
|
|
45239
|
+
const [output, code] = yield* spawner.spawn(exports_ChildProcess.make("powershell.exe", powershellArguments(dailyTaskScript), {
|
|
45240
|
+
stdin: "ignore",
|
|
45241
|
+
stderr: "inherit"
|
|
45242
|
+
})).pipe(exports_Effect.flatMap((handle) => exports_Effect.all([handle.stdout.pipe(exports_Stream.decodeText(), exports_Stream.mkString), handle.exitCode], {
|
|
45243
|
+
concurrency: "unbounded"
|
|
45244
|
+
})), exports_Effect.scoped, exports_Effect.mapError(() => new ScheduleError({ message: "Cannot ask Task Scheduler about the task." })));
|
|
45245
|
+
if (code !== 0)
|
|
45246
|
+
return yield* new ScheduleError({
|
|
45247
|
+
message: `Task Scheduler could not report the task; PowerShell exited with code ${code}.`
|
|
45248
|
+
});
|
|
45249
|
+
return exports_Option.map(exports_Option.filter(exports_Option.fromUndefinedOr(output.split(`
|
|
45250
|
+
`)[0]?.trim()), isTimeOfDay), (at) => ({
|
|
45251
|
+
at,
|
|
45252
|
+
retime: (every4) => [
|
|
45253
|
+
powershell([
|
|
45254
|
+
"$ErrorActionPreference = 'Stop'",
|
|
45255
|
+
...taskTrigger({ at, every: every4 }),
|
|
45256
|
+
`Set-ScheduledTask -TaskName ${powershellString(task)} -Trigger $trigger | Out-Null`
|
|
45257
|
+
].join(`
|
|
45258
|
+
`))
|
|
45259
|
+
],
|
|
45260
|
+
undo: []
|
|
45261
|
+
}));
|
|
45262
|
+
})
|
|
44444
45263
|
};
|
|
44445
45264
|
}
|
|
44446
45265
|
var hostScheduler = exports_Effect.gen(function* () {
|
|
@@ -44457,6 +45276,8 @@ ${contents.replaceAll(/^(?=.)/gm, " ")}`,
|
|
|
44457
45276
|
Remove: ({ file: file2 }) => `remove ${file2}
|
|
44458
45277
|
`,
|
|
44459
45278
|
Run: ({ shown }) => `run ${shown}
|
|
45279
|
+
`,
|
|
45280
|
+
Launch: ({ shown }) => `start ${shown}
|
|
44460
45281
|
`
|
|
44461
45282
|
})).join(`
|
|
44462
45283
|
`);
|
|
@@ -44474,9 +45295,29 @@ var perform = exports_Effect.fn("Schedule.perform")(function* (actions) {
|
|
|
44474
45295
|
return exports_Match.value(outcome).pipe(exports_Match.when("required", () => exports_Effect.filterOrFail(exit3, (code) => code === 0, (code) => new ScheduleError({
|
|
44475
45296
|
message: `${[program, ...args2.slice(0, 2)].join(" ")} failed with exit code ${code}. ${hint}`.trim()
|
|
44476
45297
|
}))), exports_Match.when("reported", () => exit3), exports_Match.when("silent", () => exports_Effect.ignore(exit3)), exports_Match.when("absent", () => exit3.pipe(exports_Effect.map((code) => gone.length === 0 ? code !== 0 : gone.includes(code)), exports_Effect.orElseSucceed(() => true), exports_Effect.filterOrFail((confirmed) => confirmed, () => new ScheduleError({ message: hint })))), exports_Match.exhaustive);
|
|
44477
|
-
}
|
|
45298
|
+
},
|
|
45299
|
+
Launch: ({ program, args: args2 }) => spawner.spawn(exports_ChildProcess.make(program, args2, {
|
|
45300
|
+
detached: true,
|
|
45301
|
+
stdin: "ignore",
|
|
45302
|
+
stdout: "ignore",
|
|
45303
|
+
stderr: "ignore"
|
|
45304
|
+
})).pipe(exports_Effect.flatMap((handle) => handle.unref), exports_Effect.scoped, exports_Effect.asVoid, exports_Effect.mapError(() => new ScheduleError({ message: `Cannot run ${program}.` })))
|
|
44478
45305
|
});
|
|
44479
45306
|
});
|
|
45307
|
+
var retimeDailySchedule = exports_Effect.fn("Schedule.retimeDailySchedule")(function* (directory) {
|
|
45308
|
+
if (yield* scheduleSettled(directory))
|
|
45309
|
+
return exports_Option.none();
|
|
45310
|
+
const scheduler = yield* hostScheduler.pipe(exports_Effect.option);
|
|
45311
|
+
const daily = exports_Option.isSome(scheduler) ? yield* scheduler.value.dailyJob : exports_Option.none();
|
|
45312
|
+
if (exports_Option.isSome(daily))
|
|
45313
|
+
yield* perform(daily.value.retime(defaultInterval)).pipe(exports_Effect.tapError(() => exports_Effect.ignore(perform(daily.value.undo))));
|
|
45314
|
+
yield* settleSchedule(directory);
|
|
45315
|
+
return exports_Option.map(exports_Option.all({ scheduler, daily }), ({ scheduler: scheduler2, daily: daily2 }) => ({
|
|
45316
|
+
scheduler: scheduler2.name,
|
|
45317
|
+
at: daily2.at,
|
|
45318
|
+
every: defaultInterval
|
|
45319
|
+
}));
|
|
45320
|
+
});
|
|
44480
45321
|
|
|
44481
45322
|
// packages/cli/src/copilot.ts
|
|
44482
45323
|
class CopilotError extends exports_Schema.TaggedError()("CopilotError", {
|
|
@@ -45839,6 +46680,242 @@ function wrapAnsi(string4, columns, options3) {
|
|
|
45839
46680
|
`);
|
|
45840
46681
|
}
|
|
45841
46682
|
|
|
46683
|
+
// packages/cli/src/upload.ts
|
|
46684
|
+
class SyncUnreachable extends exports_Schema.TaggedError()("SyncUnreachable", {
|
|
46685
|
+
message: exports_Schema.String
|
|
46686
|
+
}) {
|
|
46687
|
+
}
|
|
46688
|
+
|
|
46689
|
+
class SyncUnauthorized extends exports_Schema.TaggedError()("SyncUnauthorized", {
|
|
46690
|
+
status: exports_Schema.Number,
|
|
46691
|
+
message: exports_Schema.String
|
|
46692
|
+
}) {
|
|
46693
|
+
}
|
|
46694
|
+
|
|
46695
|
+
class SyncUnsupportedVersion extends exports_Schema.TaggedError()("SyncUnsupportedVersion", { message: exports_Schema.String }) {
|
|
46696
|
+
}
|
|
46697
|
+
|
|
46698
|
+
class SyncSuperseded extends exports_Schema.TaggedError()("SyncSuperseded", {
|
|
46699
|
+
message: exports_Schema.String
|
|
46700
|
+
}) {
|
|
46701
|
+
}
|
|
46702
|
+
|
|
46703
|
+
class SyncRejected extends exports_Schema.TaggedError()("SyncRejected", {
|
|
46704
|
+
status: exports_Schema.Number,
|
|
46705
|
+
message: exports_Schema.String
|
|
46706
|
+
}) {
|
|
46707
|
+
}
|
|
46708
|
+
var Acknowledgement = exports_Schema.Struct({ storedBuckets: exports_Schema.Natural });
|
|
46709
|
+
var MachineList = exports_Schema.Struct({
|
|
46710
|
+
staleAfterDays: exports_Schema.Number,
|
|
46711
|
+
from: exports_Schema.String,
|
|
46712
|
+
to: exports_Schema.String,
|
|
46713
|
+
machines: exports_Schema.Array(exports_Schema.Struct({ machineId: exports_Schema.String.check(exports_Schema.isUUID()) }))
|
|
46714
|
+
});
|
|
46715
|
+
function endpoint(server, path) {
|
|
46716
|
+
const base = new URL(server);
|
|
46717
|
+
base.pathname = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
|
|
46718
|
+
return new URL(path, base);
|
|
46719
|
+
}
|
|
46720
|
+
var VersionRejection = exports_Schema.Struct({ supportedVersions: exports_Schema.Array(exports_Schema.Int) });
|
|
46721
|
+
var readResponse = exports_Effect.fn("Sync.readResponse")(function* (response, version) {
|
|
46722
|
+
const status = response.status;
|
|
46723
|
+
if (status >= 200 && status < 300)
|
|
46724
|
+
return yield* exports_HttpClientResponse.schemaBodyJson(Acknowledgement)(response).pipe(exports_Effect.map((acknowledgement) => exports_Option.some(acknowledgement.storedBuckets)), exports_Effect.orElseSucceed(() => exports_Option.none()));
|
|
46725
|
+
if (status >= 500 || status === 408 || status === 429)
|
|
46726
|
+
return yield* new SyncUnreachable({
|
|
46727
|
+
message: `The server is temporarily unavailable (${status}); try again later.`
|
|
46728
|
+
});
|
|
46729
|
+
return yield* exports_Match.value(status).pipe(exports_Match.when(401, () => exports_Effect.fail(new SyncUnauthorized({
|
|
46730
|
+
status,
|
|
46731
|
+
message: "The server rejected the API token; create a new one in toki2."
|
|
46732
|
+
}))), exports_Match.when(403, () => exports_Effect.fail(new SyncUnauthorized({
|
|
46733
|
+
status,
|
|
46734
|
+
message: "This API token may not upload for this machine ID."
|
|
46735
|
+
}))), exports_Match.when(409, () => exports_Effect.fail(new SyncSuperseded({
|
|
46736
|
+
message: "Not stored: superseded by a newer sync from this machine. Run sync again to send this window; if every sync says this, check this machine's clock."
|
|
46737
|
+
}))), 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({
|
|
46738
|
+
message: `The server accepts payload versions ${rejection.supportedVersions.join(", ") || "none"}, not ${version}; update Toki or use a compatible token-ledger version.`
|
|
46739
|
+
}))))), exports_Match.orElse(() => exports_Effect.fail(new SyncRejected({ status, message: `The server rejected the upload (${status}).` }))));
|
|
46740
|
+
});
|
|
46741
|
+
var upload = exports_Effect.fn("Sync.upload")(function* (server, token, payload) {
|
|
46742
|
+
const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
|
|
46743
|
+
const url = endpoint(server, `ai-usage/machines/${payload.machine.id}/usage`);
|
|
46744
|
+
const request3 = yield* exports_HttpClientRequest.put(url).pipe(exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson, exports_HttpClientRequest.schemaBodyJson(SyncPayload)(payload), exports_Effect.orDie);
|
|
46745
|
+
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({
|
|
46746
|
+
while: exports_Predicate.isTagged("SyncUnreachable"),
|
|
46747
|
+
schedule: exports_Schedule.exponential("2 seconds"),
|
|
46748
|
+
times: 3
|
|
46749
|
+
}));
|
|
46750
|
+
});
|
|
46751
|
+
var hasUploaded = exports_Effect.fn("Sync.hasUploaded")(function* (server, token, id2) {
|
|
46752
|
+
const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
|
|
46753
|
+
const url = endpoint(server, "ai-usage/machines");
|
|
46754
|
+
const unanswered = new SyncUnreachable({
|
|
46755
|
+
message: `Could not ask ${url.origin} whether this machine has uploaded before.`
|
|
46756
|
+
});
|
|
46757
|
+
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));
|
|
46758
|
+
});
|
|
46759
|
+
|
|
46760
|
+
class RepricingUnavailable extends exports_Schema.TaggedError()("RepricingUnavailable", { message: exports_Schema.String }) {
|
|
46761
|
+
}
|
|
46762
|
+
|
|
46763
|
+
class RepricingRefused extends exports_Schema.TaggedError()("RepricingRefused", {
|
|
46764
|
+
status: exports_Schema.Number,
|
|
46765
|
+
message: exports_Schema.String
|
|
46766
|
+
}) {
|
|
46767
|
+
}
|
|
46768
|
+
var RepricingStatus = exports_Schema.Struct({
|
|
46769
|
+
floor: exports_Schema.DateTimeUtcFromString,
|
|
46770
|
+
providers: exports_Schema.Array(exports_Schema.Struct({
|
|
46771
|
+
provider: exports_Schema.String,
|
|
46772
|
+
from: exports_Schema.NullOr(exports_Schema.DateTimeUtcFromString),
|
|
46773
|
+
staleBuckets: exports_Schema.Natural
|
|
46774
|
+
}))
|
|
46775
|
+
});
|
|
46776
|
+
var RepricingReceipt = exports_Schema.Struct({
|
|
46777
|
+
updated: exports_Schema.Natural,
|
|
46778
|
+
unmatched: exports_Schema.Natural,
|
|
46779
|
+
beforeFloor: exports_Schema.Natural
|
|
46780
|
+
});
|
|
46781
|
+
function repricingAnswer(response, decode5) {
|
|
46782
|
+
const status = response.status;
|
|
46783
|
+
if (status >= 200 && status < 300)
|
|
46784
|
+
return decode5(response).pipe(exports_Effect.mapError(() => new RepricingRefused({ status, message: "The server's reply was not understood." })));
|
|
46785
|
+
if (status >= 500 || status === 408 || status === 429)
|
|
46786
|
+
return exports_Effect.fail(new RepricingUnavailable({ message: `The server is temporarily unavailable (${status}).` }));
|
|
46787
|
+
const message = exports_Match.value(status).pipe(exports_Match.when(401, () => "The server rejected the API token."), exports_Match.when(403, () => "This API token may not reprice for this machine ID."), exports_Match.when(404, () => "The server does not offer repricing; it may need an update."), exports_Match.orElse(() => `The server refused the request (${status}).`));
|
|
46788
|
+
return exports_Effect.fail(new RepricingRefused({ status, message }));
|
|
46789
|
+
}
|
|
46790
|
+
function exchange(server, request3, decode5, timeout4) {
|
|
46791
|
+
return exports_Effect.gen(function* () {
|
|
46792
|
+
const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
|
|
46793
|
+
return yield* client.execute(request3).pipe(exports_Effect.flatMap((response) => repricingAnswer(response, decode5)), exports_Effect.scoped, exports_Effect.timeout(timeout4), exports_Effect.catchTag(["HttpClientError", "TimeoutError"], () => exports_Effect.fail(new RepricingUnavailable({ message: `Cannot reach ${server.origin}.` }))), exports_Effect.retry({
|
|
46794
|
+
while: exports_Predicate.isTagged("RepricingUnavailable"),
|
|
46795
|
+
schedule: exports_Schedule.exponential("2 seconds"),
|
|
46796
|
+
times: 3
|
|
46797
|
+
}));
|
|
46798
|
+
});
|
|
46799
|
+
}
|
|
46800
|
+
var repricingStatus = exports_Effect.fn("Sync.repricingStatus")(function* (server, token, machineId, basis) {
|
|
46801
|
+
return yield* exchange(server, exports_HttpClientRequest.get(endpoint(server, `ai-usage/machines/${machineId}/repricing`)).pipe(exports_HttpClientRequest.setUrlParam("basis", basis), exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson), exports_HttpClientResponse.schemaBodyJson(RepricingStatus), "30 seconds");
|
|
46802
|
+
});
|
|
46803
|
+
var reprice = exports_Effect.fn("Sync.reprice")(function* (server, token, machineId, payload) {
|
|
46804
|
+
const request3 = yield* exports_HttpClientRequest.post(endpoint(server, `ai-usage/machines/${machineId}/repricing`)).pipe(exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson, exports_HttpClientRequest.schemaBodyJson(RepricePayload)(payload), exports_Effect.orDie);
|
|
46805
|
+
return yield* exchange(server, request3, exports_HttpClientResponse.schemaBodyJson(RepricingReceipt), "60 seconds");
|
|
46806
|
+
});
|
|
46807
|
+
|
|
46808
|
+
// packages/cli/src/reprice.ts
|
|
46809
|
+
var hour2 = 3600000;
|
|
46810
|
+
var isProvider = exports_Schema.is(Provider);
|
|
46811
|
+
var RepriceStep = exports_Data.taggedEnum();
|
|
46812
|
+
function repricePlan(status, scope3) {
|
|
46813
|
+
const floor = exports_DateTime.toEpochMillis(status.floor);
|
|
46814
|
+
return status.providers.flatMap((entry) => {
|
|
46815
|
+
const provider = entry.provider;
|
|
46816
|
+
if (!isProvider(provider) || !scope3.providers.has(provider) || entry.from === null)
|
|
46817
|
+
return [];
|
|
46818
|
+
const from = exports_DateTime.toEpochMillis(entry.from);
|
|
46819
|
+
const start = Math.ceil(Math.max(from, floor) / hour2) * hour2;
|
|
46820
|
+
if (start >= scope3.windowStart)
|
|
46821
|
+
return [];
|
|
46822
|
+
const finished = scope3.completed.some((completed) => completed.server === scope3.server && completed.provider === provider && completed.basis === scope3.basis && exports_DateTime.toEpochMillis(completed.from) === from && scope3.windowStart <= exports_DateTime.toEpochMillis(completed.coveredUntil));
|
|
46823
|
+
const staleBuckets = entry.staleBuckets;
|
|
46824
|
+
return [
|
|
46825
|
+
finished ? RepriceStep.Skip({ provider, from, staleBuckets }) : RepriceStep.Reprice({
|
|
46826
|
+
provider,
|
|
46827
|
+
from,
|
|
46828
|
+
range: { start, end: scope3.windowStart },
|
|
46829
|
+
staleBuckets
|
|
46830
|
+
})
|
|
46831
|
+
];
|
|
46832
|
+
});
|
|
46833
|
+
}
|
|
46834
|
+
var RepriceOutcome = exports_Data.taggedEnum();
|
|
46835
|
+
var repriceProvider = exports_Effect.fn("Sync.repriceProvider")(function* (run7, basis, step) {
|
|
46836
|
+
const { provider, from, staleBuckets } = step;
|
|
46837
|
+
let updated = 0;
|
|
46838
|
+
let unmatched = 0;
|
|
46839
|
+
let beforeFloor = 0;
|
|
46840
|
+
const failed = (message) => RepriceOutcome.Failed({ provider, from, message, updated, unmatched });
|
|
46841
|
+
const scanned = yield* run7.scan(provider, step.range).pipe(exports_Effect.result);
|
|
46842
|
+
if (exports_Result.isFailure(scanned))
|
|
46843
|
+
return failed(scanned.failure.message);
|
|
46844
|
+
const { buckets, coverage } = scanned.success;
|
|
46845
|
+
if (coverage.status === "failed")
|
|
46846
|
+
return failed("Some of its history could not be read.");
|
|
46847
|
+
if (coverage.status === "missing")
|
|
46848
|
+
return RepriceOutcome.NoHistory({ provider, from, staleBuckets });
|
|
46849
|
+
const { status, fetchedAt, source } = run7.payload.pricing;
|
|
46850
|
+
for (const chunk of repriceChunks(buckets)) {
|
|
46851
|
+
const payload = yield* RepricePayload.makeEffect({
|
|
46852
|
+
version: 1,
|
|
46853
|
+
clientVersion: run7.payload.clientVersion,
|
|
46854
|
+
pricing: { status, fetchedAt, source, basis },
|
|
46855
|
+
buckets: chunk
|
|
46856
|
+
}).pipe(exports_Effect.result);
|
|
46857
|
+
if (exports_Result.isFailure(payload))
|
|
46858
|
+
return failed("Its buckets do not satisfy the repricing contract.");
|
|
46859
|
+
const receipt = yield* reprice(run7.server, run7.token, run7.payload.machine.id, payload.success).pipe(exports_Effect.result);
|
|
46860
|
+
if (exports_Result.isFailure(receipt))
|
|
46861
|
+
return failed(receipt.failure.message);
|
|
46862
|
+
updated += receipt.success.updated;
|
|
46863
|
+
unmatched += receipt.success.unmatched;
|
|
46864
|
+
beforeFloor += receipt.success.beforeFloor;
|
|
46865
|
+
}
|
|
46866
|
+
return RepriceOutcome.Repriced({
|
|
46867
|
+
provider,
|
|
46868
|
+
from,
|
|
46869
|
+
staleBuckets,
|
|
46870
|
+
sent: buckets.length,
|
|
46871
|
+
updated,
|
|
46872
|
+
unmatched,
|
|
46873
|
+
beforeFloor
|
|
46874
|
+
});
|
|
46875
|
+
});
|
|
46876
|
+
var repriceStoredUsage = exports_Effect.fn("Sync.repriceStoredUsage")(function* (run7) {
|
|
46877
|
+
const basis = run7.payload.pricing.basis;
|
|
46878
|
+
if (basis === undefined)
|
|
46879
|
+
return [];
|
|
46880
|
+
const answer = yield* repricingStatus(run7.server, run7.token, run7.payload.machine.id, basis).pipe(exports_Effect.result);
|
|
46881
|
+
if (exports_Result.isFailure(answer))
|
|
46882
|
+
return [RepriceOutcome.Unanswered({ message: answer.failure.message })];
|
|
46883
|
+
const server = run7.server.origin;
|
|
46884
|
+
const completed = yield* loadRepricing(run7.directory);
|
|
46885
|
+
const steps = repricePlan(answer.success, {
|
|
46886
|
+
windowStart: Date.parse(run7.payload.window.start),
|
|
46887
|
+
providers: run7.providers,
|
|
46888
|
+
server,
|
|
46889
|
+
basis,
|
|
46890
|
+
completed
|
|
46891
|
+
});
|
|
46892
|
+
const outcomes = [];
|
|
46893
|
+
const finished = [];
|
|
46894
|
+
const coveredUntil = exports_DateTime.makeUnsafe(run7.payload.window.end);
|
|
46895
|
+
for (const step of steps) {
|
|
46896
|
+
const outcome = yield* RepriceStep.$match(step, {
|
|
46897
|
+
Skip: ({ provider, from, staleBuckets }) => exports_Effect.succeed(RepriceOutcome.Skipped({ provider, from, staleBuckets })),
|
|
46898
|
+
Reprice: (send) => repriceProvider(run7, basis, send)
|
|
46899
|
+
});
|
|
46900
|
+
outcomes.push(outcome);
|
|
46901
|
+
if (RepriceOutcome.$is("Repriced")(outcome))
|
|
46902
|
+
finished.push({
|
|
46903
|
+
server,
|
|
46904
|
+
provider: outcome.provider,
|
|
46905
|
+
basis,
|
|
46906
|
+
from: exports_DateTime.makeUnsafe(outcome.from),
|
|
46907
|
+
coveredUntil
|
|
46908
|
+
});
|
|
46909
|
+
}
|
|
46910
|
+
if (finished.length === 0)
|
|
46911
|
+
return outcomes;
|
|
46912
|
+
const kept = completed.filter((entry) => !finished.some((done4) => done4.server === entry.server && done4.provider === entry.provider));
|
|
46913
|
+
const saved = yield* saveRepricing(run7.directory, [...kept, ...finished]).pipe(exports_Effect.result);
|
|
46914
|
+
if (exports_Result.isFailure(saved))
|
|
46915
|
+
outcomes.push(RepriceOutcome.Unremembered({ message: saved.failure.message }));
|
|
46916
|
+
return outcomes;
|
|
46917
|
+
});
|
|
46918
|
+
|
|
45842
46919
|
// packages/cli/src/format.ts
|
|
45843
46920
|
function csvCell(value5) {
|
|
45844
46921
|
const text2 = value5 === null ? "" : String(value5);
|
|
@@ -45997,83 +47074,61 @@ function syncSummary(payload, request3, storedBuckets) {
|
|
|
45997
47074
|
].join(`
|
|
45998
47075
|
`);
|
|
45999
47076
|
}
|
|
46000
|
-
|
|
46001
|
-
|
|
46002
|
-
|
|
46003
|
-
|
|
46004
|
-
}
|
|
46005
|
-
|
|
46006
|
-
|
|
46007
|
-
|
|
46008
|
-
|
|
46009
|
-
|
|
46010
|
-
}) {
|
|
46011
|
-
|
|
46012
|
-
|
|
46013
|
-
|
|
47077
|
+
function unpricedModels(rows) {
|
|
47078
|
+
const counts = new Map;
|
|
47079
|
+
for (const row of rows)
|
|
47080
|
+
if (row.unpricedRecords > 0) {
|
|
47081
|
+
const name = `${terminalText(row.model)} (${row.provider}`;
|
|
47082
|
+
counts.set(name, (counts.get(name) ?? 0) + row.unpricedRecords);
|
|
47083
|
+
}
|
|
47084
|
+
if (counts.size === 0)
|
|
47085
|
+
return;
|
|
47086
|
+
const number4 = new Intl.NumberFormat("en-US");
|
|
47087
|
+
const ranked = [...counts].toSorted(([leftName, left], [rightName, right]) => right - left || leftName.localeCompare(rightName)).map(([name, records]) => `${name}, ${number4.format(records)} ${records === 1 ? "record" : "records"})`);
|
|
47088
|
+
const shown = ranked.slice(0, 5).join(", ");
|
|
47089
|
+
const more = ranked.length > 5 ? ` and ${ranked.length - 5} more` : "";
|
|
47090
|
+
return `Unpriced: ${shown}${more}. Configure their rates under "prices" to price them.`;
|
|
46014
47091
|
}
|
|
46015
|
-
|
|
46016
|
-
|
|
46017
|
-
message: exports_Schema.String
|
|
46018
|
-
}) {
|
|
47092
|
+
function utcHour(instant) {
|
|
47093
|
+
return `${new Date(instant).toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
|
46019
47094
|
}
|
|
46020
|
-
|
|
46021
|
-
|
|
46022
|
-
|
|
46023
|
-
|
|
46024
|
-
}) {
|
|
46025
|
-
|
|
46026
|
-
|
|
46027
|
-
|
|
46028
|
-
|
|
46029
|
-
|
|
46030
|
-
|
|
46031
|
-
|
|
46032
|
-
|
|
46033
|
-
|
|
46034
|
-
|
|
46035
|
-
|
|
46036
|
-
|
|
46037
|
-
|
|
46038
|
-
|
|
46039
|
-
|
|
46040
|
-
|
|
46041
|
-
|
|
46042
|
-
|
|
46043
|
-
|
|
46044
|
-
|
|
46045
|
-
|
|
46046
|
-
})
|
|
46047
|
-
|
|
46048
|
-
|
|
46049
|
-
|
|
46050
|
-
|
|
46051
|
-
|
|
46052
|
-
|
|
46053
|
-
|
|
46054
|
-
|
|
46055
|
-
}))), 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({
|
|
46056
|
-
message: `The server accepts payload versions ${rejection.supportedVersions.join(", ") || "none"}, not ${version}; update Toki or use a compatible token-ledger version.`
|
|
46057
|
-
}))))), exports_Match.orElse(() => exports_Effect.fail(new SyncRejected({ status, message: `The server rejected the upload (${status}).` }))));
|
|
46058
|
-
});
|
|
46059
|
-
var upload = exports_Effect.fn("Sync.upload")(function* (server, token, payload) {
|
|
46060
|
-
const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
|
|
46061
|
-
const url = endpoint(server, `ai-usage/machines/${payload.machine.id}/usage`);
|
|
46062
|
-
const request3 = yield* exports_HttpClientRequest.put(url).pipe(exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson, exports_HttpClientRequest.schemaBodyJson(SyncPayload)(payload), exports_Effect.orDie);
|
|
46063
|
-
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({
|
|
46064
|
-
while: exports_Predicate.isTagged("SyncUnreachable"),
|
|
46065
|
-
schedule: exports_Schedule.exponential("2 seconds"),
|
|
46066
|
-
times: 3
|
|
46067
|
-
}));
|
|
46068
|
-
});
|
|
46069
|
-
var hasUploaded = exports_Effect.fn("Sync.hasUploaded")(function* (server, token, id2) {
|
|
46070
|
-
const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
|
|
46071
|
-
const url = endpoint(server, "ai-usage/machines");
|
|
46072
|
-
const unanswered = new SyncUnreachable({
|
|
46073
|
-
message: `Could not ask ${url.origin} whether this machine has uploaded before.`
|
|
47095
|
+
function repriceLine(outcome) {
|
|
47096
|
+
const number4 = new Intl.NumberFormat("en-US");
|
|
47097
|
+
const buckets = (count2) => `${number4.format(count2)} ${count2 === 1 ? "bucket" : "buckets"}`;
|
|
47098
|
+
return RepriceOutcome.$match(outcome, {
|
|
47099
|
+
Repriced: ({ provider, from, staleBuckets, sent, updated, unmatched, beforeFloor }) => ({
|
|
47100
|
+
text: [
|
|
47101
|
+
`Repriced ${provider} from ${utcHour(from)}`,
|
|
47102
|
+
`${buckets(staleBuckets)} stored on an older pricing basis`,
|
|
47103
|
+
`sent ${number4.format(sent)}`,
|
|
47104
|
+
`${number4.format(updated)} updated`,
|
|
47105
|
+
`${number4.format(unmatched)} unmatched`,
|
|
47106
|
+
...beforeFloor > 0 ? [`${number4.format(beforeFloor)} before the server's floor`] : []
|
|
47107
|
+
].join(" · "),
|
|
47108
|
+
problem: false
|
|
47109
|
+
}),
|
|
47110
|
+
Skipped: ({ provider, from, staleBuckets }) => ({
|
|
47111
|
+
text: `Repricing ${provider} skipped: this machine already sent its usage from ${utcHour(from)} on this pricing basis, and cannot reproduce the ${buckets(staleBuckets)} still stored on an older one.`,
|
|
47112
|
+
problem: false
|
|
47113
|
+
}),
|
|
47114
|
+
NoHistory: ({ provider, from, staleBuckets }) => ({
|
|
47115
|
+
text: `Repricing ${provider} from ${utcHour(from)} waits: this machine found no ${provider} history to rebuild the ${buckets(staleBuckets)} stored on an older pricing basis. The next sync looks again.`,
|
|
47116
|
+
problem: false
|
|
47117
|
+
}),
|
|
47118
|
+
Failed: ({ provider, from, message, updated, unmatched }) => ({
|
|
47119
|
+
text: `Repricing ${provider} from ${utcHour(from)} did not finish: ${message}${updated + unmatched > 0 ? ` Before that, ${number4.format(updated)} updated and ${number4.format(unmatched)} unmatched.` : ""} The next sync tries again.`,
|
|
47120
|
+
problem: true
|
|
47121
|
+
}),
|
|
47122
|
+
Unanswered: ({ message }) => ({
|
|
47123
|
+
text: `Could not ask the server what to reprice: ${message} The next sync asks again.`,
|
|
47124
|
+
problem: true
|
|
47125
|
+
}),
|
|
47126
|
+
Unremembered: ({ message }) => ({
|
|
47127
|
+
text: `${message} The next sync sends its reprices again.`,
|
|
47128
|
+
problem: true
|
|
47129
|
+
})
|
|
46074
47130
|
});
|
|
46075
|
-
|
|
46076
|
-
});
|
|
47131
|
+
}
|
|
46077
47132
|
|
|
46078
47133
|
// packages/cli/src/main.ts
|
|
46079
47134
|
class CliError2 extends exports_Schema.TaggedError()("CliError", { message: exports_Schema.String }) {
|
|
@@ -46171,13 +47226,8 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
|
|
|
46171
47226
|
paths: mapping.paths.map((prefix3) => expand(prefix3, path.dirname(configFile)))
|
|
46172
47227
|
}));
|
|
46173
47228
|
const cacheRoot = yield* exports_Config.String("XDG_CACHE_HOME").pipe(exports_Config.withDefault(path.join(home, ".cache")));
|
|
46174
|
-
const basePrices = yield* loadPrices(path.join(expand(cacheRoot), "token-ledger", "prices.json"), flags.offline);
|
|
46175
|
-
const pricing = configuration.prices
|
|
46176
|
-
...basePrices,
|
|
46177
|
-
status: "custom",
|
|
46178
|
-
source: `${basePrices.source}; configuration overrides`,
|
|
46179
|
-
prices: { ...basePrices.prices, ...configuration.prices }
|
|
46180
|
-
});
|
|
47229
|
+
const basePrices = yield* loadPrices(path.join(expand(cacheRoot), "token-ledger", "prices-v2.json"), flags.offline);
|
|
47230
|
+
const pricing = configuredPricing(basePrices, configuration.prices);
|
|
46181
47231
|
if (pricing.status === "unavailable")
|
|
46182
47232
|
yield* exports_Console.error("Pricing unavailable: unknown rates remain unpriced. Configure prices or rerun online.");
|
|
46183
47233
|
const request3 = yield* ReportRequest.makeEffect({
|
|
@@ -46212,6 +47262,9 @@ var report = exports_Command.make("report", {
|
|
|
46212
47262
|
if (source.status !== "ok" || source.warnings.length > 0)
|
|
46213
47263
|
yield* exports_Console.error(`${source.provider}: ${source.status}; ${source.files} files, ${source.filesBeforeWindow} older files not opened, ${source.malformedLines} malformed lines, ${source.skippedRecords} skipped records. ${source.warnings.join(" ")}`);
|
|
46214
47264
|
}
|
|
47265
|
+
const unpriced = unpricedModels(result6.rows);
|
|
47266
|
+
if (unpriced !== undefined)
|
|
47267
|
+
yield* exports_Console.error(unpriced);
|
|
46215
47268
|
if (flags.strict && (result6.coverage.some((entry) => entry.status !== "ok") || result6.rows.some((row) => row.unpricedRecords > 0)))
|
|
46216
47269
|
process.exitCode = 2;
|
|
46217
47270
|
})).pipe(exports_Command.withDescription("Report local token consumption and API-equivalent cost by project"));
|
|
@@ -46260,10 +47313,20 @@ var sync6 = exports_Command.make("sync", {
|
|
|
46260
47313
|
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.`);
|
|
46261
47314
|
if (flags.dryRun) {
|
|
46262
47315
|
yield* exports_Console.log(JSON.stringify(first.payload, null, 2));
|
|
47316
|
+
const unpriced2 = unpricedModels(first.payload.buckets);
|
|
47317
|
+
if (unpriced2 !== undefined)
|
|
47318
|
+
yield* exports_Console.error(unpriced2);
|
|
46263
47319
|
if (flags.strict && incomplete)
|
|
46264
47320
|
process.exitCode = 2;
|
|
46265
47321
|
return;
|
|
46266
47322
|
}
|
|
47323
|
+
yield* retimeDailySchedule(directory).pipe(exports_Effect.matchEffect({
|
|
47324
|
+
onSuccess: exports_Option.match({
|
|
47325
|
+
onNone: () => exports_Effect.void,
|
|
47326
|
+
onSome: (retimed) => exports_Console.log(`Moved the scheduled sync from once a day at ${retimed.at} to ${describeTimes(retimed)}, as a ${retimed.scheduler}. To keep a daily sync, run token-ledger schedule install --every 24h.`)
|
|
47327
|
+
}),
|
|
47328
|
+
onFailure: (error2) => exports_Console.error(`Cannot move the once-a-day scheduled sync to every ${defaultInterval} hours: ${error2.message} Run token-ledger schedule install to replace it.`)
|
|
47329
|
+
}));
|
|
46267
47330
|
const refused = exports_Effect.gen(function* () {
|
|
46268
47331
|
yield* exports_Console.error("Not syncing: coverage is incomplete or usage is unpriced (--strict).");
|
|
46269
47332
|
process.exitCode = 2;
|
|
@@ -46300,7 +47363,20 @@ var sync6 = exports_Command.make("sync", {
|
|
|
46300
47363
|
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.tag("SyncSuperseded", () => 7), exports_Match.exhaustive);
|
|
46301
47364
|
return;
|
|
46302
47365
|
}
|
|
47366
|
+
const unpriced = unpricedModels(sent.payload.buckets);
|
|
47367
|
+
if (unpriced !== undefined)
|
|
47368
|
+
yield* exports_Console.error(unpriced);
|
|
46303
47369
|
yield* exports_Console.log(syncSummary(sent.payload, { ...request3, since: sent.since }, outcome.success));
|
|
47370
|
+
const repriced = yield* repriceStoredUsage({
|
|
47371
|
+
server: server.value,
|
|
47372
|
+
token: token.value,
|
|
47373
|
+
payload: sent.payload,
|
|
47374
|
+
providers: new Set(request3.sources.map((source) => source.provider)),
|
|
47375
|
+
directory,
|
|
47376
|
+
scan: (provider, range3) => ledger.repriceBuckets(request3, provider, range3)
|
|
47377
|
+
});
|
|
47378
|
+
for (const { text: text2, problem } of repriced.map(repriceLine))
|
|
47379
|
+
yield* problem ? exports_Console.error(text2) : exports_Console.log(text2);
|
|
46304
47380
|
})).pipe(exports_Command.withDescription("Upload hourly usage buckets from this machine to toki2; the server replaces the window"));
|
|
46305
47381
|
var interactive = (prompt) => exports_Prompt.run(prompt).pipe(exports_Effect.mapError(() => new CliError2({
|
|
46306
47382
|
message: "Nothing was saved. Without a terminal, pass --server and set TOKI_API_TOKEN."
|
|
@@ -46325,7 +47401,7 @@ var login = exports_Command.make("login", {
|
|
|
46325
47401
|
Next: token-ledger sync --dry-run, then token-ledger schedule install.`);
|
|
46326
47402
|
})).pipe(exports_Command.withDescription("Save the toki2 server and API token in sync.json for sync and scheduled syncs"));
|
|
46327
47403
|
var scheduleInstall = exports_Command.make("install", {
|
|
46328
|
-
every: exports_Flag.ChoiceWithValue("every", intervals).pipe(exports_Flag.withDefault(
|
|
47404
|
+
every: exports_Flag.ChoiceWithValue("every", intervals).pipe(exports_Flag.withDefault(defaultInterval), exports_Flag.withDescription(`Time between syncs; defaults to ${defaultInterval}h`)),
|
|
46329
47405
|
at: exports_Flag.String("at").pipe(exports_Flag.withDefault("12:30"), exports_Flag.withSchema(TimeOfDay), exports_Flag.withDescription("A local time, as HH:MM, that a sync runs at; defaults to 12:30")),
|
|
46330
47406
|
config: exports_Flag.String("config").pipe(exports_Flag.optional, exports_Flag.withDescription("JSON config for the scheduled sync; ./token-ledger.json is not read")),
|
|
46331
47407
|
timeZone: exports_Flag.String("time-zone").pipe(exports_Flag.withSchema(exports_Schema.TimeZoneNamedFromString), exports_Flag.optional, exports_Flag.withDescription("IANA time zone for the scheduled sync; defaults to the system zone")),
|
|
@@ -46370,6 +47446,7 @@ var scheduleInstall = exports_Command.make("install", {
|
|
|
46370
47446
|
message: "No saved server and API token. Run token-ledger login first: a scheduled sync cannot read --token or your shell's environment."
|
|
46371
47447
|
});
|
|
46372
47448
|
yield* perform(actions);
|
|
47449
|
+
yield* settleSchedule(directory).pipe(exports_Effect.ignore);
|
|
46373
47450
|
yield* exports_Console.log(`Scheduled a sync ${describeTimes(flags)} as a ${scheduler.name}, replacing any earlier schedule. Inspect it with token-ledger schedule status.`);
|
|
46374
47451
|
})).pipe(exports_Command.withDescription("Install or replace the scheduled sync; it needs the server and token saved by login"));
|
|
46375
47452
|
var scheduleStatus = exports_Command.make("status", {}, exports_Effect.fn("CLI.scheduleStatus")(function* () {
|