@ponbac/token-ledger 0.9.0 → 0.11.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 +146 -29
- package/dist/main.js +1488 -229
- 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]+):((?!\/\/).+)$/;
|
|
@@ -34480,6 +35111,7 @@ var empty14 = {
|
|
|
34480
35111
|
inherited: [],
|
|
34481
35112
|
deferred: [],
|
|
34482
35113
|
hints: [],
|
|
35114
|
+
excluded: [],
|
|
34483
35115
|
malformed: 0,
|
|
34484
35116
|
skipped: 0,
|
|
34485
35117
|
warnings: []
|
|
@@ -34508,10 +35140,12 @@ var Assistant = exports_Schema.Struct({
|
|
|
34508
35140
|
input_tokens: exports_Schema.Natural,
|
|
34509
35141
|
output_tokens: exports_Schema.Natural,
|
|
34510
35142
|
cache_read_input_tokens: exports_Schema.optionalKey(exports_Schema.Natural),
|
|
34511
|
-
cache_creation_input_tokens: exports_Schema.optionalKey(exports_Schema.Natural)
|
|
35143
|
+
cache_creation_input_tokens: exports_Schema.optionalKey(exports_Schema.Natural),
|
|
35144
|
+
cache_creation: exports_Schema.optionalKey(exports_Schema.Unknown)
|
|
34512
35145
|
})
|
|
34513
35146
|
})
|
|
34514
35147
|
});
|
|
35148
|
+
var decodeCacheCreation = exports_Schema.decodeUnknownOption(exports_Schema.Struct({ ephemeral_1h_input_tokens: exports_Schema.optionalKey(exports_Schema.Natural) }));
|
|
34515
35149
|
function claudeParser(file2) {
|
|
34516
35150
|
return {
|
|
34517
35151
|
parse(line, lineNumber) {
|
|
@@ -34527,25 +35161,26 @@ function claudeParser(file2) {
|
|
|
34527
35161
|
const usage = event.message.usage;
|
|
34528
35162
|
const session = event.sessionId ?? file2;
|
|
34529
35163
|
const id2 = event.message.id === undefined && event.requestId === undefined ? `${file2}:${lineNumber}` : `${event.message.id ?? ""}:${event.requestId ?? ""}`;
|
|
35164
|
+
const cacheWrite = usage.cache_creation_input_tokens ?? 0;
|
|
35165
|
+
const oneHour = Math.min(exports_Option.getOrNull(decodeCacheCreation(usage.cache_creation))?.ephemeral_1h_input_tokens ?? 0, cacheWrite);
|
|
35166
|
+
const record3 = {
|
|
35167
|
+
provider: "claude",
|
|
35168
|
+
id: id2,
|
|
35169
|
+
session,
|
|
35170
|
+
timestamp: ms,
|
|
35171
|
+
model: event.message.model,
|
|
35172
|
+
cwd: event.cwd ?? null,
|
|
35173
|
+
repository: null,
|
|
35174
|
+
tokens: {
|
|
35175
|
+
input: usage.input_tokens,
|
|
35176
|
+
output: usage.output_tokens,
|
|
35177
|
+
cacheRead: usage.cache_read_input_tokens ?? 0,
|
|
35178
|
+
cacheWrite
|
|
35179
|
+
}
|
|
35180
|
+
};
|
|
34530
35181
|
return {
|
|
34531
35182
|
...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
|
-
],
|
|
35183
|
+
records: [oneHour > 0 ? { ...record3, cacheWrite1h: oneHour } : record3],
|
|
34549
35184
|
warnings: event.message.id === undefined && event.requestId === undefined ? ["Some Claude records lack stable IDs; copied histories may overlap."] : []
|
|
34550
35185
|
};
|
|
34551
35186
|
}
|
|
@@ -34700,6 +35335,7 @@ var CopilotAttributes = exports_Schema.Struct({
|
|
|
34700
35335
|
"gen_ai.usage.cache_creation.input_tokens": exports_Schema.optionalKey(exports_Schema.Natural),
|
|
34701
35336
|
"gen_ai.usage.cache_read_input_tokens": exports_Schema.optionalKey(exports_Schema.Natural),
|
|
34702
35337
|
"gen_ai.usage.cache_creation_input_tokens": exports_Schema.optionalKey(exports_Schema.Natural),
|
|
35338
|
+
"gen_ai.usage.cache_write.input_tokens": exports_Schema.optionalKey(exports_Schema.Natural),
|
|
34703
35339
|
"github.copilot.git.repository": exports_Schema.optionalKey(exports_Schema.String),
|
|
34704
35340
|
"copilot_chat.repo.remote_url": exports_Schema.optionalKey(exports_Schema.String),
|
|
34705
35341
|
"session.id": exports_Schema.optionalKey(exports_Schema.String)
|
|
@@ -34732,10 +35368,12 @@ var Header = exports_Schema.Struct({
|
|
|
34732
35368
|
"gen_ai.operation.name": exports_Schema.optionalKey(exports_Schema.String)
|
|
34733
35369
|
})
|
|
34734
35370
|
});
|
|
35371
|
+
var requestId = (responseId, tokens) => `response:${responseId}#${tokens.input + tokens.cacheRead + tokens.cacheWrite}:${tokens.output}`;
|
|
35372
|
+
var isOwnerAndName = (repository) => /^[A-Za-z0-9-]+\/(?!\.{1,2}$)[A-Za-z0-9_.-]+$/.test(repository);
|
|
34735
35373
|
function repositoryReference(attributes) {
|
|
34736
35374
|
const repository = attributes["github.copilot.git.repository"];
|
|
34737
35375
|
if (repository !== undefined)
|
|
34738
|
-
return
|
|
35376
|
+
return isOwnerAndName(repository) ? RepositoryReference.Identity({ value: repository }) : RepositoryReference.Remote({ value: repository });
|
|
34739
35377
|
const remote = attributes["copilot_chat.repo.remote_url"];
|
|
34740
35378
|
return remote === undefined ? null : RepositoryReference.Remote({ value: remote });
|
|
34741
35379
|
}
|
|
@@ -34776,7 +35414,7 @@ function copilotParser(file2, chatgptRequests = new Map) {
|
|
|
34776
35414
|
if (input === undefined || output === undefined)
|
|
34777
35415
|
return skipped;
|
|
34778
35416
|
const cacheRead = a["gen_ai.usage.cache_read.input_tokens"] ?? a["gen_ai.usage.cache_read_input_tokens"] ?? 0;
|
|
34779
|
-
const cacheWrite = a["gen_ai.usage.cache_creation.input_tokens"] ?? a["gen_ai.usage.cache_creation_input_tokens"] ?? 0;
|
|
35417
|
+
const cacheWrite = a["gen_ai.usage.cache_creation.input_tokens"] ?? a["gen_ai.usage.cache_creation_input_tokens"] ?? a["gen_ai.usage.cache_write.input_tokens"] ?? 0;
|
|
34780
35418
|
if (cacheRead + cacheWrite > input)
|
|
34781
35419
|
return skipped;
|
|
34782
35420
|
const ms = span2.endTime[0] * 1000 + Math.floor(span2.endTime[1] / 1e6);
|
|
@@ -34805,12 +35443,16 @@ function copilotParser(file2, chatgptRequests = new Map) {
|
|
|
34805
35443
|
for (const { spanKey, responseId, isSpan } of candidates)
|
|
34806
35444
|
if (!isSpan && spanKey !== undefined && responseId !== undefined)
|
|
34807
35445
|
eventResponses.set(spanKey, (eventResponses.get(spanKey) ?? new Set).add(responseId));
|
|
34808
|
-
const
|
|
35446
|
+
const responses = candidates.map((candidate) => {
|
|
34809
35447
|
const shared = candidate.isSpan && candidate.responseId === undefined && candidate.spanKey !== undefined ? eventResponses.get(candidate.spanKey) : undefined;
|
|
34810
|
-
|
|
35448
|
+
return shared?.size === 1 ? [...shared][0] : candidate.responseId;
|
|
35449
|
+
});
|
|
35450
|
+
const identified = candidates.map((candidate, index2) => {
|
|
35451
|
+
const responseId = responses[index2];
|
|
34811
35452
|
if (responseId === undefined)
|
|
34812
35453
|
return candidate;
|
|
34813
|
-
const
|
|
35454
|
+
const id2 = requestId(responseId, candidate.record.tokens);
|
|
35455
|
+
const record3 = { ...candidate.record, id: id2 };
|
|
34814
35456
|
const routed = chatgptRequests.get(responseId);
|
|
34815
35457
|
if (routed === undefined)
|
|
34816
35458
|
return { ...candidate, responseId, record: record3 };
|
|
@@ -34821,8 +35463,7 @@ function copilotParser(file2, chatgptRequests = new Map) {
|
|
|
34821
35463
|
hinted: routed.repository === null ? null : RepositoryReference.Remote({ value: routed.repository })
|
|
34822
35464
|
};
|
|
34823
35465
|
});
|
|
34824
|
-
const
|
|
34825
|
-
for (const candidate of identified) {
|
|
35466
|
+
const inheritedRepository = (candidate) => {
|
|
34826
35467
|
let repository = candidate.record.repository;
|
|
34827
35468
|
let key = candidate.spanKey;
|
|
34828
35469
|
const visited = new Set;
|
|
@@ -34832,6 +35473,11 @@ function copilotParser(file2, chatgptRequests = new Map) {
|
|
|
34832
35473
|
repository = ancestor?.repository ?? null;
|
|
34833
35474
|
key = ancestor?.parent;
|
|
34834
35475
|
}
|
|
35476
|
+
return repository;
|
|
35477
|
+
};
|
|
35478
|
+
const preferred = new Map;
|
|
35479
|
+
for (const candidate of identified) {
|
|
35480
|
+
const repository = inheritedRepository(candidate);
|
|
34835
35481
|
const resolved = { ...candidate, record: { ...candidate.record, repository } };
|
|
34836
35482
|
const previous = preferred.get(resolved.record.id);
|
|
34837
35483
|
if (previous === undefined)
|
|
@@ -34903,6 +35549,144 @@ var copilotDatabaseLines = exports_Effect.fn("Copilot.readDatabase")(function* (
|
|
|
34903
35549
|
}).pipe(exports_Effect.scoped);
|
|
34904
35550
|
});
|
|
34905
35551
|
|
|
35552
|
+
// packages/core/src/providers/copilot-session.ts
|
|
35553
|
+
var Workspace = exports_Schema.Struct({
|
|
35554
|
+
cwd: exports_Schema.optionalKey(exports_Schema.String),
|
|
35555
|
+
repository: exports_Schema.optionalKey(exports_Schema.String),
|
|
35556
|
+
repositoryHost: exports_Schema.optionalKey(exports_Schema.String),
|
|
35557
|
+
hostType: exports_Schema.optionalKey(exports_Schema.String),
|
|
35558
|
+
pendingGitContext: exports_Schema.optionalKey(exports_Schema.Boolean)
|
|
35559
|
+
});
|
|
35560
|
+
var SessionStart = exports_Schema.Struct({
|
|
35561
|
+
type: exports_Schema.Literal("session.start"),
|
|
35562
|
+
data: exports_Schema.Struct({
|
|
35563
|
+
sessionId: exports_Schema.NonEmptyString,
|
|
35564
|
+
context: exports_Schema.optionalKey(Workspace)
|
|
35565
|
+
})
|
|
35566
|
+
});
|
|
35567
|
+
var ContextChanged = exports_Schema.Struct({
|
|
35568
|
+
type: exports_Schema.Literal("session.context_changed"),
|
|
35569
|
+
data: Workspace
|
|
35570
|
+
});
|
|
35571
|
+
var Resumed = exports_Schema.Struct({
|
|
35572
|
+
type: exports_Schema.Literal("session.resume"),
|
|
35573
|
+
data: exports_Schema.Struct({ context: exports_Schema.optionalKey(Workspace) })
|
|
35574
|
+
});
|
|
35575
|
+
var UsageEvent = exports_Schema.Struct({
|
|
35576
|
+
type: exports_Schema.Literal("session.usage_record"),
|
|
35577
|
+
timestamp: exports_Schema.String,
|
|
35578
|
+
data: exports_Schema.Struct({
|
|
35579
|
+
usage: exports_Schema.Struct({
|
|
35580
|
+
model: exports_Schema.NonEmptyString,
|
|
35581
|
+
inputTokens: exports_Schema.Natural,
|
|
35582
|
+
outputTokens: exports_Schema.Natural,
|
|
35583
|
+
cacheReadTokens: exports_Schema.optionalKey(exports_Schema.Natural),
|
|
35584
|
+
cacheWriteTokens: exports_Schema.optionalKey(exports_Schema.Natural),
|
|
35585
|
+
isByok: exports_Schema.optionalKey(exports_Schema.Boolean),
|
|
35586
|
+
apiCallId: exports_Schema.optionalKey(exports_Schema.NonEmptyString),
|
|
35587
|
+
accounting: exports_Schema.optionalKey(exports_Schema.Struct({
|
|
35588
|
+
sourceSessionId: exports_Schema.optionalKey(exports_Schema.NonEmptyString),
|
|
35589
|
+
usageId: exports_Schema.optionalKey(exports_Schema.NonEmptyString)
|
|
35590
|
+
}))
|
|
35591
|
+
})
|
|
35592
|
+
})
|
|
35593
|
+
});
|
|
35594
|
+
var Header2 = exports_Schema.Struct({ type: exports_Schema.String });
|
|
35595
|
+
var decodeHeader = exports_Schema.decodeUnknownOption(Header2);
|
|
35596
|
+
var decodeStart = exports_Schema.decodeUnknownOption(SessionStart);
|
|
35597
|
+
var decodeChange = exports_Schema.decodeUnknownOption(ContextChanged);
|
|
35598
|
+
var decodeResume = exports_Schema.decodeUnknownOption(Resumed);
|
|
35599
|
+
var decodeUsage = exports_Schema.decodeUnknownOption(UsageEvent);
|
|
35600
|
+
function insideSession(entry) {
|
|
35601
|
+
return entry.split(/[\\/]/).at(-3) === "session-state";
|
|
35602
|
+
}
|
|
35603
|
+
var accounting = [
|
|
35604
|
+
'"session.start"',
|
|
35605
|
+
'"session.resume"',
|
|
35606
|
+
'"session.context_changed"',
|
|
35607
|
+
'"session.usage_record"'
|
|
35608
|
+
];
|
|
35609
|
+
function githubRemote(workspace) {
|
|
35610
|
+
const { hostType, repository, repositoryHost = "github.com" } = workspace;
|
|
35611
|
+
return hostType === "github" && repository !== undefined && isOwnerAndName(repository) && /^[a-z0-9.-]+(?::\d+)?$/i.test(repositoryHost) ? RepositoryReference.Remote({ value: `https://${repositoryHost}/${repository}` }) : null;
|
|
35612
|
+
}
|
|
35613
|
+
function isSessionEvents(file2) {
|
|
35614
|
+
return insideSession(file2) && file2.split(/[\\/]/).at(-1) === "events.jsonl";
|
|
35615
|
+
}
|
|
35616
|
+
function copilotSessionParser(file2, chatgptRequests) {
|
|
35617
|
+
let session;
|
|
35618
|
+
let cwd = null;
|
|
35619
|
+
let repository = null;
|
|
35620
|
+
const settle = (workspace) => {
|
|
35621
|
+
if (workspace?.pendingGitContext === true)
|
|
35622
|
+
return;
|
|
35623
|
+
cwd = workspace?.cwd || null;
|
|
35624
|
+
repository = workspace === undefined ? null : githubRemote(workspace);
|
|
35625
|
+
};
|
|
35626
|
+
return {
|
|
35627
|
+
parse(line) {
|
|
35628
|
+
if (!accounting.some((type4) => line.includes(type4)))
|
|
35629
|
+
return empty14;
|
|
35630
|
+
const raw2 = exports_Option.getOrNull(decodeJson(line));
|
|
35631
|
+
const type3 = exports_Option.getOrNull(decodeHeader(raw2))?.type;
|
|
35632
|
+
if (type3 === "session.start") {
|
|
35633
|
+
const event2 = exports_Option.getOrNull(decodeStart(raw2));
|
|
35634
|
+
if (event2 === null)
|
|
35635
|
+
return empty14;
|
|
35636
|
+
session = event2.data.sessionId;
|
|
35637
|
+
settle(event2.data.context);
|
|
35638
|
+
return empty14;
|
|
35639
|
+
}
|
|
35640
|
+
if (type3 === "session.context_changed") {
|
|
35641
|
+
settle(exports_Option.getOrNull(decodeChange(raw2))?.data ?? undefined);
|
|
35642
|
+
return empty14;
|
|
35643
|
+
}
|
|
35644
|
+
if (type3 === "session.resume") {
|
|
35645
|
+
const context3 = exports_Option.getOrNull(decodeResume(raw2))?.data.context;
|
|
35646
|
+
if (context3 !== undefined)
|
|
35647
|
+
settle(context3);
|
|
35648
|
+
return empty14;
|
|
35649
|
+
}
|
|
35650
|
+
if (type3 !== "session.usage_record")
|
|
35651
|
+
return empty14;
|
|
35652
|
+
const event = exports_Option.getOrNull(decodeUsage(raw2));
|
|
35653
|
+
if (event === null)
|
|
35654
|
+
return skipped;
|
|
35655
|
+
const usage = event.data.usage;
|
|
35656
|
+
const usageId = usage.accounting?.usageId;
|
|
35657
|
+
const cacheRead = usage.cacheReadTokens ?? 0;
|
|
35658
|
+
const cacheWrite = usage.cacheWriteTokens ?? 0;
|
|
35659
|
+
const tokens = {
|
|
35660
|
+
input: usage.inputTokens - cacheRead - cacheWrite,
|
|
35661
|
+
output: usage.outputTokens,
|
|
35662
|
+
cacheRead,
|
|
35663
|
+
cacheWrite
|
|
35664
|
+
};
|
|
35665
|
+
const id2 = usage.apiCallId !== undefined ? requestId(usage.apiCallId, tokens) : usageId === undefined ? undefined : `usage:${usageId}`;
|
|
35666
|
+
const routed = usage.apiCallId === undefined ? undefined : chatgptRequests?.get(usage.apiCallId);
|
|
35667
|
+
if (usage.isByok === true && chatgptRequests !== undefined && routed === undefined)
|
|
35668
|
+
return id2 === undefined ? empty14 : { ...empty14, excluded: [id2] };
|
|
35669
|
+
const ms = timestamp(event.timestamp);
|
|
35670
|
+
if (ms === null || id2 === undefined || cacheRead + cacheWrite > usage.inputTokens)
|
|
35671
|
+
return skipped;
|
|
35672
|
+
const record3 = {
|
|
35673
|
+
provider: "copilot",
|
|
35674
|
+
id: id2,
|
|
35675
|
+
session: usage.accounting?.sourceSessionId ?? session ?? file2,
|
|
35676
|
+
timestamp: ms,
|
|
35677
|
+
model: usage.model,
|
|
35678
|
+
cwd,
|
|
35679
|
+
repository: repository ?? (routed === undefined || routed.repository === null ? null : RepositoryReference.Remote({ value: routed.repository })),
|
|
35680
|
+
tokens
|
|
35681
|
+
};
|
|
35682
|
+
return {
|
|
35683
|
+
...empty14,
|
|
35684
|
+
records: [routed === undefined ? record3 : { ...record3, billingProvider: "codex" }]
|
|
35685
|
+
};
|
|
35686
|
+
}
|
|
35687
|
+
};
|
|
35688
|
+
}
|
|
35689
|
+
|
|
34906
35690
|
// packages/core/src/providers/grok.ts
|
|
34907
35691
|
var Counts2 = exports_Schema.Struct({
|
|
34908
35692
|
inputTokens: exports_Schema.Natural,
|
|
@@ -34948,6 +35732,7 @@ function grokParser(file2) {
|
|
|
34948
35732
|
if (cacheRead + cacheWrite > count2.inputTokens)
|
|
34949
35733
|
return skipped;
|
|
34950
35734
|
records.push({
|
|
35735
|
+
aggregate: true,
|
|
34951
35736
|
provider: "grok",
|
|
34952
35737
|
id: `${session}:${promptId ?? `${file2}:${lineNumber}`}:${model}`,
|
|
34953
35738
|
session,
|
|
@@ -35181,7 +35966,7 @@ function opencodeHistory(nativePath) {
|
|
|
35181
35966
|
|
|
35182
35967
|
// packages/core/src/providers/pi.ts
|
|
35183
35968
|
var decodeKind = exports_Schema.decodeUnknownOption(exports_Schema.Struct({ type: exports_Schema.String }));
|
|
35184
|
-
var
|
|
35969
|
+
var decodeHeader2 = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
|
|
35185
35970
|
id: exports_Schema.optionalKey(exports_Schema.String),
|
|
35186
35971
|
timestamp: exports_Schema.optionalKey(exports_Schema.String),
|
|
35187
35972
|
cwd: exports_Schema.optionalKey(exports_Schema.String),
|
|
@@ -35206,6 +35991,7 @@ var decodeCounts = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
|
|
|
35206
35991
|
}));
|
|
35207
35992
|
var unattributedModel2 = "unknown";
|
|
35208
35993
|
var chatGptSignIn = "openai-codex";
|
|
35994
|
+
var copilotSignIn = "github-copilot";
|
|
35209
35995
|
function piParser(file2) {
|
|
35210
35996
|
let session = file2;
|
|
35211
35997
|
let cwd = null;
|
|
@@ -35220,7 +36006,7 @@ function piParser(file2) {
|
|
|
35220
36006
|
if (type3 === "session") {
|
|
35221
36007
|
if (sawHeader)
|
|
35222
36008
|
return empty14;
|
|
35223
|
-
const header = exports_Option.getOrNull(
|
|
36009
|
+
const header = exports_Option.getOrNull(decodeHeader2(raw2));
|
|
35224
36010
|
if (header === null)
|
|
35225
36011
|
return malformed;
|
|
35226
36012
|
sawHeader = true;
|
|
@@ -35248,7 +36034,7 @@ function piParser(file2) {
|
|
|
35248
36034
|
if (stamp === null || names === null || count2 === null || ms === null)
|
|
35249
36035
|
return skipped;
|
|
35250
36036
|
const model = attributed ? names.responseModel ?? names.model : undefined;
|
|
35251
|
-
const
|
|
36037
|
+
const own = {
|
|
35252
36038
|
provider: "pi",
|
|
35253
36039
|
id: stamp.id === undefined ? `${file2}:${lineNumber}` : `${stamp.id}:${stamp.timestamp}`,
|
|
35254
36040
|
session,
|
|
@@ -35258,6 +36044,7 @@ function piParser(file2) {
|
|
|
35258
36044
|
repository: null,
|
|
35259
36045
|
tokens: count2
|
|
35260
36046
|
};
|
|
36047
|
+
const record3 = attributed && names.provider === copilotSignIn && totalTokens(count2) > 0 ? { ...own, billingProvider: "copilot" } : type3 === "message" && carrier.role === "toolResult" ? { ...own, aggregate: true } : own;
|
|
35261
36048
|
const copied = forked !== null && ms < forked;
|
|
35262
36049
|
return {
|
|
35263
36050
|
...empty14,
|
|
@@ -35277,7 +36064,7 @@ function piParser(file2) {
|
|
|
35277
36064
|
}
|
|
35278
36065
|
|
|
35279
36066
|
// packages/core/src/sync.ts
|
|
35280
|
-
import { createHash as
|
|
36067
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
35281
36068
|
var hour = 3600000;
|
|
35282
36069
|
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
36070
|
const ms = Date.parse(s);
|
|
@@ -35351,25 +36138,62 @@ var SyncPayload = exports_Schema.Struct({
|
|
|
35351
36138
|
pricing: exports_Schema.Struct({
|
|
35352
36139
|
status: PriceBook.fields.status,
|
|
35353
36140
|
fetchedAt: exports_Schema.NullOr(UtcInstant),
|
|
35354
|
-
source: Text
|
|
36141
|
+
source: Text,
|
|
36142
|
+
basis: exports_Schema.optionalKey(PricingBasis)
|
|
35355
36143
|
}),
|
|
35356
36144
|
buckets: exports_Schema.Array(SyncBucket),
|
|
35357
36145
|
coverage: exports_Schema.Array(SyncCoverage),
|
|
35358
36146
|
providerHints: exports_Schema.optionalKey(exports_Schema.Array(ProviderHint)),
|
|
35359
36147
|
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])), {
|
|
36148
|
+
}).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
36149
|
expected: "unique bucket keys, coverage providers, and plan hints, and a version carrying every bucket"
|
|
35369
36150
|
}), exports_Schema.makeFilter((payload) => {
|
|
35370
36151
|
const replaced = replacedProviders(payload.coverage);
|
|
35371
36152
|
return [...payload.buckets, ...payload.providerHints ?? []].every((entry) => replaced.has(entry.provider) && entry.hourStart >= payload.window.start && entry.hourStart < payload.window.end);
|
|
35372
36153
|
}));
|
|
36154
|
+
var maxRepriceBuckets = 20000;
|
|
36155
|
+
var RepricePayload = exports_Schema.Struct({
|
|
36156
|
+
version: exports_Schema.Literal(1),
|
|
36157
|
+
clientVersion: NonEmptyText,
|
|
36158
|
+
pricing: exports_Schema.Struct({
|
|
36159
|
+
status: PriceBook.fields.status,
|
|
36160
|
+
fetchedAt: exports_Schema.NullOr(UtcInstant),
|
|
36161
|
+
source: Text,
|
|
36162
|
+
basis: PricingBasis
|
|
36163
|
+
}),
|
|
36164
|
+
buckets: exports_Schema.Array(SyncBucket).check(exports_Schema.isMaxLength(maxRepriceBuckets))
|
|
36165
|
+
}).check(exports_Schema.makeFilter((payload) => distinct(payload.buckets, bucketKey), {
|
|
36166
|
+
expected: "unique bucket keys"
|
|
36167
|
+
}));
|
|
36168
|
+
var maxRepriceBytes = 12 * 1024 * 1024;
|
|
36169
|
+
function repriceChunks(buckets) {
|
|
36170
|
+
const chunks2 = [];
|
|
36171
|
+
let chunk = [];
|
|
36172
|
+
let bytes2 = 0;
|
|
36173
|
+
for (const bucket of buckets) {
|
|
36174
|
+
const size7 = Buffer.byteLength(JSON.stringify(bucket)) + 1;
|
|
36175
|
+
if (chunk.length > 0 && (chunk.length >= maxRepriceBuckets || bytes2 + size7 > maxRepriceBytes)) {
|
|
36176
|
+
chunks2.push(chunk);
|
|
36177
|
+
chunk = [];
|
|
36178
|
+
bytes2 = 0;
|
|
36179
|
+
}
|
|
36180
|
+
chunk.push(bucket);
|
|
36181
|
+
bytes2 += size7;
|
|
36182
|
+
}
|
|
36183
|
+
if (chunk.length > 0)
|
|
36184
|
+
chunks2.push(chunk);
|
|
36185
|
+
return chunks2;
|
|
36186
|
+
}
|
|
36187
|
+
function bucketKey(bucket) {
|
|
36188
|
+
return JSON.stringify([
|
|
36189
|
+
bucket.hourStart,
|
|
36190
|
+
bucket.sessionKey,
|
|
36191
|
+
bucket.project,
|
|
36192
|
+
bucket.provider,
|
|
36193
|
+
bucket.billingProvider ?? null,
|
|
36194
|
+
bucket.model
|
|
36195
|
+
]);
|
|
36196
|
+
}
|
|
35373
36197
|
function distinct(items, key) {
|
|
35374
36198
|
return new Set(items.map(key)).size === items.length;
|
|
35375
36199
|
}
|
|
@@ -35381,7 +36205,7 @@ function hourRange(range3) {
|
|
|
35381
36205
|
};
|
|
35382
36206
|
}
|
|
35383
36207
|
function sessionKey(provider, session) {
|
|
35384
|
-
return
|
|
36208
|
+
return createHash3("sha256").update(`${provider}\x00${session}`).digest("hex").slice(0, 32);
|
|
35385
36209
|
}
|
|
35386
36210
|
function sessionBuckets(pricing) {
|
|
35387
36211
|
const totals = new Map;
|
|
@@ -35399,7 +36223,7 @@ function sessionBuckets(pricing) {
|
|
|
35399
36223
|
model
|
|
35400
36224
|
]);
|
|
35401
36225
|
const previous = totals.get(key);
|
|
35402
|
-
const cost =
|
|
36226
|
+
const cost = priceRecord(record3, pricing).usd;
|
|
35403
36227
|
totals.set(key, {
|
|
35404
36228
|
record: previous?.record ?? record3,
|
|
35405
36229
|
project,
|
|
@@ -35490,6 +36314,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35490
36314
|
const scan2 = exports_Effect.fn("Ledger.scan")(function* (request3, range3, locate, collect2, notice, onWarning) {
|
|
35491
36315
|
const hints = yield* (notice !== undefined && request3.billingHints !== undefined && request3.sources.some((source) => source.provider === "copilot") ? readBillingHints(request3.billingHints).pipe(exports_Effect.provideService(exports_FileSystem.FileSystem, fs), exports_Effect.provideService(exports_Path.Path, path)) : exports_Effect.succeed(new Map)).pipe(exports_Effect.result);
|
|
35492
36316
|
const chatgptRequests = exports_Result.isSuccess(hints) ? hints.success : new Map;
|
|
36317
|
+
const routing = notice !== undefined && request3.billingHints !== undefined && exports_Result.isSuccess(hints) ? chatgptRequests : undefined;
|
|
35493
36318
|
if (exports_Result.isFailure(hints))
|
|
35494
36319
|
yield* onWarning?.(`Billing hints: ${hints.failure.message} Copilot will not be uploaded. Repair the hints and rerun sync with --since <first missed day>.`) ?? exports_Effect.void;
|
|
35495
36320
|
const resolveProject = yield* projectResolver(request3.projects).pipe(exports_Effect.provideService(exports_FileSystem.FileSystem, fs), exports_Effect.provideService(exports_Path.Path, path));
|
|
@@ -35499,6 +36324,8 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35499
36324
|
const coverage = [];
|
|
35500
36325
|
const inherited = [];
|
|
35501
36326
|
const deferred = [];
|
|
36327
|
+
const copilotCopies = [];
|
|
36328
|
+
const copilotExcluded = new Set;
|
|
35502
36329
|
const opencode = opencodeHistory((value5) => path.normalize(value5));
|
|
35503
36330
|
for (const source of request3.sources) {
|
|
35504
36331
|
let files = 0;
|
|
@@ -35519,18 +36346,24 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35519
36346
|
seen.add(id2);
|
|
35520
36347
|
collect2(record3, yield* resolveProject(record3, source.project), slot);
|
|
35521
36348
|
});
|
|
35522
|
-
const accept2 = exports_Effect.fn("Ledger.acceptRecords")(function* (result6) {
|
|
36349
|
+
const accept2 = exports_Effect.fn("Ledger.acceptRecords")(function* (result6, fromSession = false) {
|
|
35523
36350
|
malformedLines += result6.malformed;
|
|
35524
36351
|
skippedRecords += result6.skipped;
|
|
35525
36352
|
for (const warning of result6.warnings)
|
|
35526
36353
|
warnings.add(warning);
|
|
36354
|
+
for (const id2 of result6.excluded)
|
|
36355
|
+
copilotExcluded.add(id2);
|
|
35527
36356
|
for (const hint of result6.hints) {
|
|
35528
36357
|
if (locate(hint.timestamp) !== undefined)
|
|
35529
36358
|
notice?.({ provider: source.provider, ...hint });
|
|
35530
36359
|
}
|
|
35531
36360
|
for (const record3 of result6.records) {
|
|
35532
36361
|
const slot = locate(record3.timestamp);
|
|
35533
|
-
if (slot
|
|
36362
|
+
if (slot === undefined || totalTokens(record3.tokens) === 0)
|
|
36363
|
+
continue;
|
|
36364
|
+
if (source.provider === "copilot")
|
|
36365
|
+
copilotCopies.push({ record: record3, slot, fromSession, place });
|
|
36366
|
+
else
|
|
35534
36367
|
yield* place(record3, slot);
|
|
35535
36368
|
}
|
|
35536
36369
|
for (const record3 of result6.inherited) {
|
|
@@ -35563,7 +36396,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35563
36396
|
return;
|
|
35564
36397
|
}
|
|
35565
36398
|
visitedFiles.add(identity3);
|
|
35566
|
-
const parser = exports_Match.value(source.provider).pipe(exports_Match.when("codex", () => codexParser(canonical)), exports_Match.when("claude", () => claudeParser(canonical)), exports_Match.when("grok", () => grokParser(canonical)), exports_Match.when("copilot", () => copilot ?? copilotParser(canonical)), exports_Match.when("pi", () => piParser(canonical)), exports_Match.when("opencode", () => opencode.parser(opencodeFile(path, canonical))), exports_Match.exhaustive);
|
|
36399
|
+
const parser = exports_Match.value(source.provider).pipe(exports_Match.when("codex", () => codexParser(canonical)), exports_Match.when("claude", () => claudeParser(canonical)), exports_Match.when("grok", () => grokParser(canonical)), exports_Match.when("copilot", () => isSessionEvents(file2) ? copilotSessionParser(canonical, routing) : copilot ?? copilotParser(canonical)), exports_Match.when("pi", () => piParser(canonical)), exports_Match.when("opencode", () => opencode.parser(opencodeFile(path, canonical))), exports_Match.exhaustive);
|
|
35567
36400
|
let lineNumber = 0;
|
|
35568
36401
|
files++;
|
|
35569
36402
|
const lines = source.provider === "copilot" && canonical.endsWith(".db") ? exports_Stream.fromIterableEffect(copilotDatabaseLines(canonical)) : source.provider === "opencode" ? opencodeFile(path, canonical) === "database" ? exports_Stream.fromIterableEffect(opencodeDatabaseLines(canonical, range3.start, range3.end)) : exports_Stream.fromEffect(fs.readFileString(canonical)) : fs.stream(canonical).pipe(exports_Stream.decodeText, exports_Stream.splitLines);
|
|
@@ -35571,9 +36404,9 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35571
36404
|
lineNumber++;
|
|
35572
36405
|
if (!line.trim())
|
|
35573
36406
|
return;
|
|
35574
|
-
yield* accept2(parser.parse(line, lineNumber));
|
|
36407
|
+
yield* accept2(parser.parse(line, lineNumber), parser !== copilot);
|
|
35575
36408
|
})));
|
|
35576
|
-
if (
|
|
36409
|
+
if (parser !== copilot && parser.finish !== undefined)
|
|
35577
36410
|
yield* accept2(parser.finish());
|
|
35578
36411
|
});
|
|
35579
36412
|
const pending = [source.path];
|
|
@@ -35627,6 +36460,21 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35627
36460
|
warnings: [...warnings]
|
|
35628
36461
|
}));
|
|
35629
36462
|
}
|
|
36463
|
+
const requests = new Map;
|
|
36464
|
+
for (const copy4 of copilotCopies)
|
|
36465
|
+
requests.set(copy4.record.id, [...requests.get(copy4.record.id) ?? [], copy4]);
|
|
36466
|
+
for (const [id2, copies] of requests) {
|
|
36467
|
+
const primary = copies.find((copy4) => copy4.fromSession) ?? copies[0];
|
|
36468
|
+
if (primary === undefined)
|
|
36469
|
+
continue;
|
|
36470
|
+
if (copilotExcluded.has(id2))
|
|
36471
|
+
seen.add(`copilot:${id2}`);
|
|
36472
|
+
const repository = primary.record.repository ?? copies.find((copy4) => copy4.record.repository !== null)?.record.repository ?? null;
|
|
36473
|
+
yield* primary.place({ ...primary.record, repository }, primary.slot);
|
|
36474
|
+
for (const copy4 of copies)
|
|
36475
|
+
if (copy4 !== primary)
|
|
36476
|
+
yield* copy4.place(copy4.record, copy4.slot);
|
|
36477
|
+
}
|
|
35630
36478
|
for (const legacy of deferred)
|
|
35631
36479
|
yield* legacy;
|
|
35632
36480
|
for (const copy4 of inherited)
|
|
@@ -35639,14 +36487,14 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35639
36487
|
const rows = new Map;
|
|
35640
36488
|
const coverage = yield* scan2(request3, window, window.dayOf, (record3, { project }, day) => {
|
|
35641
36489
|
const key = JSON.stringify([project, day, record3.provider, record3.model]);
|
|
35642
|
-
const
|
|
36490
|
+
const { usd, base } = priceRecord(record3, request3.pricing);
|
|
35643
36491
|
rows.set(key, {
|
|
35644
36492
|
project,
|
|
35645
36493
|
day,
|
|
35646
36494
|
provider: record3.provider,
|
|
35647
36495
|
model: record3.model,
|
|
35648
|
-
pricePerMillion:
|
|
35649
|
-
...addUsage(rows.get(key), record3.tokens,
|
|
36496
|
+
pricePerMillion: base,
|
|
36497
|
+
...addUsage(rows.get(key), record3.tokens, usd)
|
|
35650
36498
|
});
|
|
35651
36499
|
});
|
|
35652
36500
|
return UsageReport.make({
|
|
@@ -35656,11 +36504,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35656
36504
|
timeZone: request3.timeZone.id,
|
|
35657
36505
|
currency: "USD",
|
|
35658
36506
|
costBasis: "api-equivalent",
|
|
35659
|
-
pricing:
|
|
35660
|
-
status: request3.pricing.status,
|
|
35661
|
-
fetchedAt: request3.pricing.fetchedAt,
|
|
35662
|
-
source: request3.pricing.source
|
|
35663
|
-
},
|
|
36507
|
+
pricing: provenance(request3.pricing),
|
|
35664
36508
|
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
36509
|
coverage
|
|
35666
36510
|
});
|
|
@@ -35678,7 +36522,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35678
36522
|
const snapshotAt = yield* exports_Clock.currentTimeMillis;
|
|
35679
36523
|
const coverage = yield* scan2(request3, { start: from, end: requested.end }, (timestamp2) => timestamp2 >= from && timestamp2 < requested.end ? timestamp2 : undefined, (record3, attribution, timestamp2) => {
|
|
35680
36524
|
earliest = Math.min(earliest, timestamp2);
|
|
35681
|
-
buckets.add(record3, attribution
|
|
36525
|
+
buckets.add(record3, uploadedProject(attribution));
|
|
35682
36526
|
}, (plan) => {
|
|
35683
36527
|
earliest = Math.min(earliest, plan.timestamp);
|
|
35684
36528
|
hints.add(plan);
|
|
@@ -35699,11 +36543,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35699
36543
|
},
|
|
35700
36544
|
currency: "USD",
|
|
35701
36545
|
costBasis: "api-equivalent",
|
|
35702
|
-
pricing:
|
|
35703
|
-
status: request3.pricing.status,
|
|
35704
|
-
fetchedAt: request3.pricing.fetchedAt,
|
|
35705
|
-
source: request3.pricing.source
|
|
35706
|
-
},
|
|
36546
|
+
pricing: provenance(request3.pricing),
|
|
35707
36547
|
buckets: uploadedBuckets,
|
|
35708
36548
|
coverage: summary,
|
|
35709
36549
|
providerHints: hints.finish().filter((hint) => replaced.has(hint.provider)),
|
|
@@ -35713,13 +36553,45 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35713
36553
|
})));
|
|
35714
36554
|
return { payload, since };
|
|
35715
36555
|
});
|
|
36556
|
+
const repriceBuckets = exports_Effect.fn("Ledger.repriceBuckets")(function* (input, provider, range3) {
|
|
36557
|
+
const request3 = yield* decode5(input);
|
|
36558
|
+
const hours2 = hourRange(range3);
|
|
36559
|
+
if (hours2.start !== range3.start || hours2.end !== range3.end || range3.start >= range3.end)
|
|
36560
|
+
return yield* new InvalidRequest({ message: "Expected a range of whole UTC hours." });
|
|
36561
|
+
const buckets = sessionBuckets(request3.pricing);
|
|
36562
|
+
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)), () => {
|
|
36563
|
+
return;
|
|
36564
|
+
});
|
|
36565
|
+
const summary = providerCoverage(coverage).find((entry) => entry.provider === provider) ?? {
|
|
36566
|
+
provider,
|
|
36567
|
+
status: "missing",
|
|
36568
|
+
files: 0,
|
|
36569
|
+
filesBeforeWindow: 0,
|
|
36570
|
+
unreadable: 0,
|
|
36571
|
+
malformedLines: 0,
|
|
36572
|
+
skippedRecords: 0,
|
|
36573
|
+
duplicates: 0
|
|
36574
|
+
};
|
|
36575
|
+
return {
|
|
36576
|
+
buckets: replacedProviders([summary]).has(provider) ? buckets.finish() : [],
|
|
36577
|
+
coverage: summary
|
|
36578
|
+
};
|
|
36579
|
+
});
|
|
35716
36580
|
return Ledger.of({
|
|
35717
36581
|
report,
|
|
35718
36582
|
syncPayload: (request3, client, onWarning) => exports_Effect.map(payloadFrom(request3, client, false, onWarning), ({ payload }) => payload),
|
|
35719
|
-
historyPayload: (request3, client, onWarning) => payloadFrom(request3, client, true, onWarning)
|
|
36583
|
+
historyPayload: (request3, client, onWarning) => payloadFrom(request3, client, true, onWarning),
|
|
36584
|
+
repriceBuckets
|
|
35720
36585
|
});
|
|
35721
36586
|
}));
|
|
35722
36587
|
}
|
|
36588
|
+
function uploadedProject(attribution) {
|
|
36589
|
+
return attribution.shareable ? attribution.project : unattributed;
|
|
36590
|
+
}
|
|
36591
|
+
function provenance(pricing) {
|
|
36592
|
+
const { status, fetchedAt, source } = pricing;
|
|
36593
|
+
return pricing.basis === undefined ? { status, fetchedAt, source } : { status, fetchedAt, source, basis: pricing.basis };
|
|
36594
|
+
}
|
|
35723
36595
|
function acceptsFile(path, source, file2) {
|
|
35724
36596
|
if (source.path === file2)
|
|
35725
36597
|
return true;
|
|
@@ -35727,7 +36599,9 @@ function acceptsFile(path, source, file2) {
|
|
|
35727
36599
|
return file2.endsWith("/updates.jsonl") || file2.endsWith("\\updates.jsonl");
|
|
35728
36600
|
if (source.provider === "opencode")
|
|
35729
36601
|
return opencodeFile(path, file2) !== "database" || opencodeDatabaseName.test(path.basename(file2));
|
|
35730
|
-
|
|
36602
|
+
if (source.provider === "copilot")
|
|
36603
|
+
return insideSession(file2) ? isSessionEvents(file2) : file2.endsWith(".jsonl") || file2.endsWith(".db");
|
|
36604
|
+
return file2.endsWith(".jsonl");
|
|
35731
36605
|
}
|
|
35732
36606
|
function opencodeFile(path, file2) {
|
|
35733
36607
|
const name = path.basename(file2);
|
|
@@ -35749,10 +36623,14 @@ var opencodeElsewhere = new Set([
|
|
|
35749
36623
|
"tool-output"
|
|
35750
36624
|
]);
|
|
35751
36625
|
function descends(path, source, directory) {
|
|
35752
|
-
|
|
36626
|
+
if (directory === source.path)
|
|
36627
|
+
return true;
|
|
36628
|
+
if (source.provider === "copilot")
|
|
36629
|
+
return !insideSession(directory);
|
|
36630
|
+
return source.provider !== "opencode" || !opencodeElsewhere.has(path.basename(directory));
|
|
35753
36631
|
}
|
|
35754
36632
|
function settledBefore(path, source, file2, info2, cutoff) {
|
|
35755
|
-
if (source.path === file2 || source.provider === "copilot" || source.provider === "opencode" && opencodeFile(path, file2) !== "message")
|
|
36633
|
+
if (source.path === file2 || source.provider === "copilot" && !isSessionEvents(file2) || source.provider === "opencode" && opencodeFile(path, file2) !== "message")
|
|
35756
36634
|
return false;
|
|
35757
36635
|
return exports_Option.isSome(info2.mtime) && info2.mtime.value.getTime() < cutoff;
|
|
35758
36636
|
}
|
|
@@ -43055,7 +43933,7 @@ var runWith2 = (command, config) => {
|
|
|
43055
43933
|
// packages/cli/package.json
|
|
43056
43934
|
var package_default = {
|
|
43057
43935
|
name: "@ponbac/token-ledger",
|
|
43058
|
-
version: "0.
|
|
43936
|
+
version: "0.11.0",
|
|
43059
43937
|
private: true,
|
|
43060
43938
|
type: "module",
|
|
43061
43939
|
bin: {
|
|
@@ -44220,6 +45098,51 @@ var saveSyncSettings = exports_Effect.fn("Settings.saveSync")(function* (directo
|
|
|
44220
45098
|
}).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: `Cannot save ${file2}.` })));
|
|
44221
45099
|
return file2;
|
|
44222
45100
|
});
|
|
45101
|
+
var CompletedReprice = exports_Schema.Struct({
|
|
45102
|
+
server: exports_Schema.String,
|
|
45103
|
+
provider: Provider,
|
|
45104
|
+
basis: PricingBasis,
|
|
45105
|
+
from: exports_Schema.DateTimeUtcFromString,
|
|
45106
|
+
coveredUntil: exports_Schema.DateTimeUtcFromString
|
|
45107
|
+
});
|
|
45108
|
+
var Repricing = exports_Schema.Struct({
|
|
45109
|
+
version: exports_Schema.Literal(1),
|
|
45110
|
+
completed: exports_Schema.Array(CompletedReprice)
|
|
45111
|
+
});
|
|
45112
|
+
var loadRepricing = exports_Effect.fn("Settings.loadRepricing")(function* (directory) {
|
|
45113
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
45114
|
+
const path = yield* exports_Path.Path;
|
|
45115
|
+
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(() => []));
|
|
45116
|
+
});
|
|
45117
|
+
var saveRepricing = exports_Effect.fn("Settings.saveRepricing")(function* (directory, completed) {
|
|
45118
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
45119
|
+
const path = yield* exports_Path.Path;
|
|
45120
|
+
const file2 = path.join(directory, "repricing.json");
|
|
45121
|
+
yield* exports_Effect.gen(function* () {
|
|
45122
|
+
const repricing = yield* exports_Schema.encodeEffect(Repricing)({ version: 1, completed });
|
|
45123
|
+
yield* fs.makeDirectory(directory, { recursive: true });
|
|
45124
|
+
const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
|
|
45125
|
+
directory,
|
|
45126
|
+
prefix: ".repricing-"
|
|
45127
|
+
});
|
|
45128
|
+
const temporary = path.join(temporaryDirectory, "repricing.json");
|
|
45129
|
+
yield* fs.writeFileString(temporary, `${JSON.stringify(repricing, null, 2)}
|
|
45130
|
+
`, { flag: "wx" });
|
|
45131
|
+
yield* fs.rename(temporary, file2);
|
|
45132
|
+
}).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: "Cannot save repricing.json in the settings directory." })));
|
|
45133
|
+
});
|
|
45134
|
+
var ScheduleSettings = exports_Schema.Struct({ version: exports_Schema.Literal(1) });
|
|
45135
|
+
var scheduleSettled = exports_Effect.fn("Settings.scheduleSettled")(function* (directory) {
|
|
45136
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
45137
|
+
const path = yield* exports_Path.Path;
|
|
45138
|
+
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));
|
|
45139
|
+
});
|
|
45140
|
+
var settleSchedule = exports_Effect.fn("Settings.settleSchedule")(function* (directory) {
|
|
45141
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
45142
|
+
const path = yield* exports_Path.Path;
|
|
45143
|
+
yield* fs.makeDirectory(directory, { recursive: true }).pipe(exports_Effect.andThen(fs.writeFileString(path.join(directory, "schedule.json"), `${JSON.stringify({ version: 1 }, null, 2)}
|
|
45144
|
+
`)), exports_Effect.mapError(() => new SettingsError({ message: "Cannot save schedule.json in the settings directory." })));
|
|
45145
|
+
});
|
|
44223
45146
|
|
|
44224
45147
|
// packages/cli/src/schedule.ts
|
|
44225
45148
|
class ScheduleError extends exports_Schema.TaggedError()("ScheduleError", {
|
|
@@ -44237,6 +45160,8 @@ var intervals = [
|
|
|
44237
45160
|
["12h", 12],
|
|
44238
45161
|
["24h", 24]
|
|
44239
45162
|
];
|
|
45163
|
+
var defaultInterval = 2;
|
|
45164
|
+
var isTimeOfDay = exports_Schema.is(TimeOfDay);
|
|
44240
45165
|
function syncTimes(job) {
|
|
44241
45166
|
const hour2 = Number(job.at.slice(0, 2));
|
|
44242
45167
|
const minute = job.at.slice(3);
|
|
@@ -44248,6 +45173,11 @@ var unit = "token-ledger-sync";
|
|
|
44248
45173
|
var label = "com.github.ponbac.token-ledger.sync";
|
|
44249
45174
|
var task = "token-ledger sync";
|
|
44250
45175
|
var packageSpec = "@ponbac/token-ledger@latest";
|
|
45176
|
+
var readJob = (file2) => exports_Effect.gen(function* () {
|
|
45177
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
45178
|
+
return (yield* fs.exists(file2)) ? exports_Option.some(yield* fs.readFileString(file2)) : exports_Option.none();
|
|
45179
|
+
}).pipe(exports_Effect.mapError(() => new ScheduleError({ message: `Cannot read ${file2}.` })));
|
|
45180
|
+
var dailyAt = (hour2, minute) => exports_Option.filter(exports_Option.some(`${hour2.padStart(2, "0")}:${minute.padStart(2, "0")}`), isTimeOfDay);
|
|
44251
45181
|
function run6(outcome, program, args2, hint = "") {
|
|
44252
45182
|
return Action3.Run({
|
|
44253
45183
|
program,
|
|
@@ -44279,6 +45209,17 @@ var posixScript = (job) => [
|
|
|
44279
45209
|
].join("; ");
|
|
44280
45210
|
var posixJob = (job) => quotable(job, /\p{Cc}/u, "a control character");
|
|
44281
45211
|
var systemdQuoted = (value5) => `"${value5.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("%", "%%").replaceAll("$", () => "$$")}"`;
|
|
45212
|
+
var timerUnit = (job) => `[Unit]
|
|
45213
|
+
Description=AI usage sync ${job.every === 24 ? "once a day" : `every ${job.every}h`}
|
|
45214
|
+
|
|
45215
|
+
[Timer]
|
|
45216
|
+
OnCalendar=*-*-* ${syncTimes(job).map((time2) => time2.slice(0, 2)).join(",")}:${job.at.slice(3)}:00
|
|
45217
|
+
Persistent=true
|
|
45218
|
+
RandomizedDelaySec=10m
|
|
45219
|
+
|
|
45220
|
+
[Install]
|
|
45221
|
+
WantedBy=timers.target
|
|
45222
|
+
`;
|
|
44282
45223
|
function systemdTimer(directory) {
|
|
44283
45224
|
const service4 = `${directory}/${unit}.service`;
|
|
44284
45225
|
const timer = `${directory}/${unit}.timer`;
|
|
@@ -44297,20 +45238,7 @@ Type=oneshot
|
|
|
44297
45238
|
ExecStart=/bin/sh -lc ${systemdQuoted(posixScript(job2))}
|
|
44298
45239
|
`
|
|
44299
45240
|
}),
|
|
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
|
-
}),
|
|
45241
|
+
Action3.Write({ file: timer, contents: timerUnit(job2) }),
|
|
44314
45242
|
systemctl("required", ["daemon-reload"]),
|
|
44315
45243
|
systemctl("required", ["enable", `${unit}.timer`]),
|
|
44316
45244
|
systemctl("required", ["restart", `${unit}.timer`])
|
|
@@ -44326,31 +45254,45 @@ WantedBy=timers.target
|
|
|
44326
45254
|
gone: [3, 4]
|
|
44327
45255
|
})
|
|
44328
45256
|
],
|
|
44329
|
-
status: [systemctl("reported", ["status", "--no-pager", `${unit}.timer`, `${unit}.service`])]
|
|
45257
|
+
status: [systemctl("reported", ["status", "--no-pager", `${unit}.timer`, `${unit}.service`])],
|
|
45258
|
+
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) => ({
|
|
45259
|
+
at,
|
|
45260
|
+
retime: (every4) => [
|
|
45261
|
+
Action3.Write({ file: timer, contents: timerUnit({ at, every: every4 }) }),
|
|
45262
|
+
systemctl("required", ["daemon-reload"]),
|
|
45263
|
+
systemctl("required", ["try-restart", `${unit}.timer`])
|
|
45264
|
+
],
|
|
45265
|
+
undo: [Action3.Write({ file: timer, contents })]
|
|
45266
|
+
})))))
|
|
44330
45267
|
};
|
|
44331
45268
|
}
|
|
44332
45269
|
var xmlText = (value5) => value5.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
45270
|
+
var calendarInterval = (job) => `<key>StartCalendarInterval</key>
|
|
45271
|
+
<array>
|
|
45272
|
+
${syncTimes(job).map((time2) => {
|
|
45273
|
+
const [hour2, minute] = time2.split(":").map(Number);
|
|
45274
|
+
return ` <dict>
|
|
45275
|
+
<key>Hour</key>
|
|
45276
|
+
<integer>${hour2}</integer>
|
|
45277
|
+
<key>Minute</key>
|
|
45278
|
+
<integer>${minute}</integer>
|
|
45279
|
+
</dict>`;
|
|
45280
|
+
}).join(`
|
|
45281
|
+
`)}
|
|
45282
|
+
</array>`;
|
|
45283
|
+
var startCalendarInterval = /<key>StartCalendarInterval<\/key>\s*(?:<dict>[\s\S]*?<\/dict>|<array>[\s\S]*?<\/array>)/;
|
|
45284
|
+
var hourAndMinute = /<key>Hour<\/key>\s*<integer>(\d{1,2})<\/integer>\s*<key>Minute<\/key>\s*<integer>(\d{1,2})<\/integer>/g;
|
|
45285
|
+
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
45286
|
function launchAgent(home, uid) {
|
|
44334
45287
|
const plist = `${home}/Library/LaunchAgents/${label}.plist`;
|
|
44335
45288
|
const log3 = `${home}/Library/Logs/${unit}.log`;
|
|
44336
45289
|
const domain = `gui/${uid}`;
|
|
44337
45290
|
return {
|
|
44338
45291
|
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"?>
|
|
45292
|
+
install: (job) => posixJob(job).pipe(exports_Effect.map((job2) => [
|
|
45293
|
+
Action3.Write({
|
|
45294
|
+
file: plist,
|
|
45295
|
+
contents: `<?xml version="1.0" encoding="UTF-8"?>
|
|
44354
45296
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
44355
45297
|
<plist version="1.0">
|
|
44356
45298
|
<dict>
|
|
@@ -44364,10 +45306,7 @@ function launchAgent(home, uid) {
|
|
|
44364
45306
|
</array>
|
|
44365
45307
|
<key>RunAtLoad</key>
|
|
44366
45308
|
<true/>
|
|
44367
|
-
|
|
44368
|
-
<array>
|
|
44369
|
-
${times}
|
|
44370
|
-
</array>
|
|
45309
|
+
${calendarInterval(job2)}
|
|
44371
45310
|
<key>StandardOutPath</key>
|
|
44372
45311
|
<string>${xmlText(log3)}</string>
|
|
44373
45312
|
<key>StandardErrorPath</key>
|
|
@@ -44375,17 +45314,35 @@ ${times}
|
|
|
44375
45314
|
</dict>
|
|
44376
45315
|
</plist>
|
|
44377
45316
|
`
|
|
44378
|
-
|
|
44379
|
-
|
|
44380
|
-
|
|
44381
|
-
|
|
44382
|
-
})),
|
|
45317
|
+
}),
|
|
45318
|
+
run6("silent", "launchctl", ["bootout", `${domain}/${label}`]),
|
|
45319
|
+
run6("required", "launchctl", ["bootstrap", domain, plist])
|
|
45320
|
+
])),
|
|
44383
45321
|
uninstall: [
|
|
44384
45322
|
run6("reported", "launchctl", ["bootout", `${domain}/${label}`]),
|
|
44385
45323
|
Action3.Remove({ file: plist }),
|
|
44386
45324
|
run6("absent", "launchctl", ["print", `${domain}/${label}`], "The agent is still loaded; launchd's reason is shown above.")
|
|
44387
45325
|
],
|
|
44388
|
-
status: [run6("reported", "launchctl", ["print", `${domain}/${label}`])]
|
|
45326
|
+
status: [run6("reported", "launchctl", ["print", `${domain}/${label}`])],
|
|
45327
|
+
dailyJob: readJob(plist).pipe(exports_Effect.map(exports_Option.flatMap((contents) => exports_Option.flatMap(exports_Option.fromNullishOr(startCalendarInterval.exec(contents)), ([block]) => {
|
|
45328
|
+
const times = [...block.matchAll(hourAndMinute)];
|
|
45329
|
+
const [, hour2 = "", minute = ""] = times[0] ?? [];
|
|
45330
|
+
return times.length === 1 ? exports_Option.map(dailyAt(hour2, minute), (at) => ({
|
|
45331
|
+
at,
|
|
45332
|
+
retime: (every4) => [
|
|
45333
|
+
Action3.Write({
|
|
45334
|
+
file: plist,
|
|
45335
|
+
contents: contents.replace(startCalendarInterval, () => calendarInterval({ at, every: every4 }))
|
|
45336
|
+
}),
|
|
45337
|
+
Action3.Launch({
|
|
45338
|
+
program: "/bin/sh",
|
|
45339
|
+
args: ["-c", reloadAgent, "sh", `${domain}/${label}`, domain, plist],
|
|
45340
|
+
shown: `/bin/sh -c '${reloadAgent}' sh ${domain}/${label} ${domain} ${plist}`
|
|
45341
|
+
})
|
|
45342
|
+
],
|
|
45343
|
+
undo: [Action3.Write({ file: plist, contents })]
|
|
45344
|
+
})) : exports_Option.none();
|
|
45345
|
+
}))))
|
|
44389
45346
|
};
|
|
44390
45347
|
}
|
|
44391
45348
|
var cmdWord = (value5) => /^[\w@+=:,./\\-]+$/.test(value5) ? value5 : `"${value5}"`;
|
|
@@ -44396,6 +45353,33 @@ var powershellArguments = (script) => [
|
|
|
44396
45353
|
Buffer.from(script, "utf16le").toString("base64")
|
|
44397
45354
|
];
|
|
44398
45355
|
var jscriptString = (value5) => JSON.stringify(value5).replaceAll(/[\u007f-\uffff]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
45356
|
+
var taskTrigger = (job) => [
|
|
45357
|
+
`$trigger = New-ScheduledTaskTrigger -Daily -At '${syncTimes(job)[0]}'`,
|
|
45358
|
+
...job.every === 24 ? [] : [
|
|
45359
|
+
`$trigger.Repetition = (New-ScheduledTaskTrigger -Once -At '${syncTimes(job)[0]}' -RepetitionInterval (New-TimeSpan -Hours ${job.every}) -RepetitionDuration (New-TimeSpan -Hours ${24 - job.every})).Repetition`
|
|
45360
|
+
]
|
|
45361
|
+
];
|
|
45362
|
+
var dailyTaskScript = [
|
|
45363
|
+
"$ErrorActionPreference = 'Stop'",
|
|
45364
|
+
`try { $task = Get-ScheduledTask -TaskName ${powershellString(task)} }`,
|
|
45365
|
+
"catch { if ($_.CategoryInfo.Category -eq 'ObjectNotFound') { exit 0 }; throw }",
|
|
45366
|
+
"if (@($task.Triggers).Count -eq 1) {",
|
|
45367
|
+
" $trigger = @($task.Triggers)[0]",
|
|
45368
|
+
" if ($trigger.CimClass.CimClassName -eq 'MSFT_TaskDailyTrigger' -and $trigger.DaysInterval -eq 1 -and -not $trigger.Repetition.Interval) {",
|
|
45369
|
+
" $trigger.StartBoundary.Substring(11, 5)",
|
|
45370
|
+
" }",
|
|
45371
|
+
"}"
|
|
45372
|
+
].join(`
|
|
45373
|
+
`);
|
|
45374
|
+
var powershell = (script) => Action3.Run({
|
|
45375
|
+
program: "powershell.exe",
|
|
45376
|
+
args: powershellArguments(script),
|
|
45377
|
+
shown: `powershell.exe ${powershellOptions.join(" ")} <the script below, as UTF-16LE Base64>
|
|
45378
|
+
${script}`,
|
|
45379
|
+
outcome: "required",
|
|
45380
|
+
hint: "",
|
|
45381
|
+
gone: []
|
|
45382
|
+
});
|
|
44399
45383
|
function taskScheduler(file2) {
|
|
44400
45384
|
return {
|
|
44401
45385
|
name: "Task Scheduler task",
|
|
@@ -44409,10 +45393,7 @@ function taskScheduler(file2) {
|
|
|
44409
45393
|
"$ErrorActionPreference = 'Stop'",
|
|
44410
45394
|
"$ProgressPreference = 'SilentlyContinue'",
|
|
44411
45395
|
`$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
|
-
],
|
|
45396
|
+
...taskTrigger(job2),
|
|
44416
45397
|
"$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
|
|
44417
45398
|
`Register-ScheduledTask -TaskName ${powershellString(task)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`
|
|
44418
45399
|
].join(`
|
|
@@ -44424,15 +45405,7 @@ function taskScheduler(file2) {
|
|
|
44424
45405
|
WScript.Quit(shell.Run(${jscriptString(`cmd.exe /d /v:off /s /c "${command}"`)}, 0, true));
|
|
44425
45406
|
`
|
|
44426
45407
|
}),
|
|
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
|
-
})
|
|
45408
|
+
powershell(script)
|
|
44436
45409
|
];
|
|
44437
45410
|
})),
|
|
44438
45411
|
uninstall: [
|
|
@@ -44440,7 +45413,33 @@ ${script}`,
|
|
|
44440
45413
|
run6("absent", "schtasks.exe", ["/Query", "/TN", task], "The task is still registered; Task Scheduler's reason is shown above."),
|
|
44441
45414
|
Action3.Remove({ file: file2 })
|
|
44442
45415
|
],
|
|
44443
|
-
status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])]
|
|
45416
|
+
status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])],
|
|
45417
|
+
dailyJob: exports_Effect.gen(function* () {
|
|
45418
|
+
const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
|
|
45419
|
+
const [output, code] = yield* spawner.spawn(exports_ChildProcess.make("powershell.exe", powershellArguments(dailyTaskScript), {
|
|
45420
|
+
stdin: "ignore",
|
|
45421
|
+
stderr: "inherit"
|
|
45422
|
+
})).pipe(exports_Effect.flatMap((handle) => exports_Effect.all([handle.stdout.pipe(exports_Stream.decodeText(), exports_Stream.mkString), handle.exitCode], {
|
|
45423
|
+
concurrency: "unbounded"
|
|
45424
|
+
})), exports_Effect.scoped, exports_Effect.mapError(() => new ScheduleError({ message: "Cannot ask Task Scheduler about the task." })));
|
|
45425
|
+
if (code !== 0)
|
|
45426
|
+
return yield* new ScheduleError({
|
|
45427
|
+
message: `Task Scheduler could not report the task; PowerShell exited with code ${code}.`
|
|
45428
|
+
});
|
|
45429
|
+
return exports_Option.map(exports_Option.filter(exports_Option.fromUndefinedOr(output.split(`
|
|
45430
|
+
`)[0]?.trim()), isTimeOfDay), (at) => ({
|
|
45431
|
+
at,
|
|
45432
|
+
retime: (every4) => [
|
|
45433
|
+
powershell([
|
|
45434
|
+
"$ErrorActionPreference = 'Stop'",
|
|
45435
|
+
...taskTrigger({ at, every: every4 }),
|
|
45436
|
+
`Set-ScheduledTask -TaskName ${powershellString(task)} -Trigger $trigger | Out-Null`
|
|
45437
|
+
].join(`
|
|
45438
|
+
`))
|
|
45439
|
+
],
|
|
45440
|
+
undo: []
|
|
45441
|
+
}));
|
|
45442
|
+
})
|
|
44444
45443
|
};
|
|
44445
45444
|
}
|
|
44446
45445
|
var hostScheduler = exports_Effect.gen(function* () {
|
|
@@ -44457,6 +45456,8 @@ ${contents.replaceAll(/^(?=.)/gm, " ")}`,
|
|
|
44457
45456
|
Remove: ({ file: file2 }) => `remove ${file2}
|
|
44458
45457
|
`,
|
|
44459
45458
|
Run: ({ shown }) => `run ${shown}
|
|
45459
|
+
`,
|
|
45460
|
+
Launch: ({ shown }) => `start ${shown}
|
|
44460
45461
|
`
|
|
44461
45462
|
})).join(`
|
|
44462
45463
|
`);
|
|
@@ -44474,9 +45475,29 @@ var perform = exports_Effect.fn("Schedule.perform")(function* (actions) {
|
|
|
44474
45475
|
return exports_Match.value(outcome).pipe(exports_Match.when("required", () => exports_Effect.filterOrFail(exit3, (code) => code === 0, (code) => new ScheduleError({
|
|
44475
45476
|
message: `${[program, ...args2.slice(0, 2)].join(" ")} failed with exit code ${code}. ${hint}`.trim()
|
|
44476
45477
|
}))), 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
|
-
}
|
|
45478
|
+
},
|
|
45479
|
+
Launch: ({ program, args: args2 }) => spawner.spawn(exports_ChildProcess.make(program, args2, {
|
|
45480
|
+
detached: true,
|
|
45481
|
+
stdin: "ignore",
|
|
45482
|
+
stdout: "ignore",
|
|
45483
|
+
stderr: "ignore"
|
|
45484
|
+
})).pipe(exports_Effect.flatMap((handle) => handle.unref), exports_Effect.scoped, exports_Effect.asVoid, exports_Effect.mapError(() => new ScheduleError({ message: `Cannot run ${program}.` })))
|
|
44478
45485
|
});
|
|
44479
45486
|
});
|
|
45487
|
+
var retimeDailySchedule = exports_Effect.fn("Schedule.retimeDailySchedule")(function* (directory) {
|
|
45488
|
+
if (yield* scheduleSettled(directory))
|
|
45489
|
+
return exports_Option.none();
|
|
45490
|
+
const scheduler = yield* hostScheduler.pipe(exports_Effect.option);
|
|
45491
|
+
const daily = exports_Option.isSome(scheduler) ? yield* scheduler.value.dailyJob : exports_Option.none();
|
|
45492
|
+
if (exports_Option.isSome(daily))
|
|
45493
|
+
yield* perform(daily.value.retime(defaultInterval)).pipe(exports_Effect.tapError(() => exports_Effect.ignore(perform(daily.value.undo))));
|
|
45494
|
+
yield* settleSchedule(directory);
|
|
45495
|
+
return exports_Option.map(exports_Option.all({ scheduler, daily }), ({ scheduler: scheduler2, daily: daily2 }) => ({
|
|
45496
|
+
scheduler: scheduler2.name,
|
|
45497
|
+
at: daily2.at,
|
|
45498
|
+
every: defaultInterval
|
|
45499
|
+
}));
|
|
45500
|
+
});
|
|
44480
45501
|
|
|
44481
45502
|
// packages/cli/src/copilot.ts
|
|
44482
45503
|
class CopilotError extends exports_Schema.TaggedError()("CopilotError", {
|
|
@@ -45839,6 +46860,242 @@ function wrapAnsi(string4, columns, options3) {
|
|
|
45839
46860
|
`);
|
|
45840
46861
|
}
|
|
45841
46862
|
|
|
46863
|
+
// packages/cli/src/upload.ts
|
|
46864
|
+
class SyncUnreachable extends exports_Schema.TaggedError()("SyncUnreachable", {
|
|
46865
|
+
message: exports_Schema.String
|
|
46866
|
+
}) {
|
|
46867
|
+
}
|
|
46868
|
+
|
|
46869
|
+
class SyncUnauthorized extends exports_Schema.TaggedError()("SyncUnauthorized", {
|
|
46870
|
+
status: exports_Schema.Number,
|
|
46871
|
+
message: exports_Schema.String
|
|
46872
|
+
}) {
|
|
46873
|
+
}
|
|
46874
|
+
|
|
46875
|
+
class SyncUnsupportedVersion extends exports_Schema.TaggedError()("SyncUnsupportedVersion", { message: exports_Schema.String }) {
|
|
46876
|
+
}
|
|
46877
|
+
|
|
46878
|
+
class SyncSuperseded extends exports_Schema.TaggedError()("SyncSuperseded", {
|
|
46879
|
+
message: exports_Schema.String
|
|
46880
|
+
}) {
|
|
46881
|
+
}
|
|
46882
|
+
|
|
46883
|
+
class SyncRejected extends exports_Schema.TaggedError()("SyncRejected", {
|
|
46884
|
+
status: exports_Schema.Number,
|
|
46885
|
+
message: exports_Schema.String
|
|
46886
|
+
}) {
|
|
46887
|
+
}
|
|
46888
|
+
var Acknowledgement = exports_Schema.Struct({ storedBuckets: exports_Schema.Natural });
|
|
46889
|
+
var MachineList = exports_Schema.Struct({
|
|
46890
|
+
staleAfterDays: exports_Schema.Number,
|
|
46891
|
+
from: exports_Schema.String,
|
|
46892
|
+
to: exports_Schema.String,
|
|
46893
|
+
machines: exports_Schema.Array(exports_Schema.Struct({ machineId: exports_Schema.String.check(exports_Schema.isUUID()) }))
|
|
46894
|
+
});
|
|
46895
|
+
function endpoint(server, path) {
|
|
46896
|
+
const base = new URL(server);
|
|
46897
|
+
base.pathname = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
|
|
46898
|
+
return new URL(path, base);
|
|
46899
|
+
}
|
|
46900
|
+
var VersionRejection = exports_Schema.Struct({ supportedVersions: exports_Schema.Array(exports_Schema.Int) });
|
|
46901
|
+
var readResponse = exports_Effect.fn("Sync.readResponse")(function* (response, version) {
|
|
46902
|
+
const status = response.status;
|
|
46903
|
+
if (status >= 200 && status < 300)
|
|
46904
|
+
return yield* exports_HttpClientResponse.schemaBodyJson(Acknowledgement)(response).pipe(exports_Effect.map((acknowledgement) => exports_Option.some(acknowledgement.storedBuckets)), exports_Effect.orElseSucceed(() => exports_Option.none()));
|
|
46905
|
+
if (status >= 500 || status === 408 || status === 429)
|
|
46906
|
+
return yield* new SyncUnreachable({
|
|
46907
|
+
message: `The server is temporarily unavailable (${status}); try again later.`
|
|
46908
|
+
});
|
|
46909
|
+
return yield* exports_Match.value(status).pipe(exports_Match.when(401, () => exports_Effect.fail(new SyncUnauthorized({
|
|
46910
|
+
status,
|
|
46911
|
+
message: "The server rejected the API token; create a new one in toki2."
|
|
46912
|
+
}))), exports_Match.when(403, () => exports_Effect.fail(new SyncUnauthorized({
|
|
46913
|
+
status,
|
|
46914
|
+
message: "This API token may not upload for this machine ID."
|
|
46915
|
+
}))), exports_Match.when(409, () => exports_Effect.fail(new SyncSuperseded({
|
|
46916
|
+
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."
|
|
46917
|
+
}))), 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({
|
|
46918
|
+
message: `The server accepts payload versions ${rejection.supportedVersions.join(", ") || "none"}, not ${version}; update Toki or use a compatible token-ledger version.`
|
|
46919
|
+
}))))), exports_Match.orElse(() => exports_Effect.fail(new SyncRejected({ status, message: `The server rejected the upload (${status}).` }))));
|
|
46920
|
+
});
|
|
46921
|
+
var upload = exports_Effect.fn("Sync.upload")(function* (server, token, payload) {
|
|
46922
|
+
const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
|
|
46923
|
+
const url = endpoint(server, `ai-usage/machines/${payload.machine.id}/usage`);
|
|
46924
|
+
const request3 = yield* exports_HttpClientRequest.put(url).pipe(exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson, exports_HttpClientRequest.schemaBodyJson(SyncPayload)(payload), exports_Effect.orDie);
|
|
46925
|
+
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({
|
|
46926
|
+
while: exports_Predicate.isTagged("SyncUnreachable"),
|
|
46927
|
+
schedule: exports_Schedule.exponential("2 seconds"),
|
|
46928
|
+
times: 3
|
|
46929
|
+
}));
|
|
46930
|
+
});
|
|
46931
|
+
var hasUploaded = exports_Effect.fn("Sync.hasUploaded")(function* (server, token, id2) {
|
|
46932
|
+
const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
|
|
46933
|
+
const url = endpoint(server, "ai-usage/machines");
|
|
46934
|
+
const unanswered = new SyncUnreachable({
|
|
46935
|
+
message: `Could not ask ${url.origin} whether this machine has uploaded before.`
|
|
46936
|
+
});
|
|
46937
|
+
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));
|
|
46938
|
+
});
|
|
46939
|
+
|
|
46940
|
+
class RepricingUnavailable extends exports_Schema.TaggedError()("RepricingUnavailable", { message: exports_Schema.String }) {
|
|
46941
|
+
}
|
|
46942
|
+
|
|
46943
|
+
class RepricingRefused extends exports_Schema.TaggedError()("RepricingRefused", {
|
|
46944
|
+
status: exports_Schema.Number,
|
|
46945
|
+
message: exports_Schema.String
|
|
46946
|
+
}) {
|
|
46947
|
+
}
|
|
46948
|
+
var RepricingStatus = exports_Schema.Struct({
|
|
46949
|
+
floor: exports_Schema.DateTimeUtcFromString,
|
|
46950
|
+
providers: exports_Schema.Array(exports_Schema.Struct({
|
|
46951
|
+
provider: exports_Schema.String,
|
|
46952
|
+
from: exports_Schema.NullOr(exports_Schema.DateTimeUtcFromString),
|
|
46953
|
+
staleBuckets: exports_Schema.Natural
|
|
46954
|
+
}))
|
|
46955
|
+
});
|
|
46956
|
+
var RepricingReceipt = exports_Schema.Struct({
|
|
46957
|
+
updated: exports_Schema.Natural,
|
|
46958
|
+
unmatched: exports_Schema.Natural,
|
|
46959
|
+
beforeFloor: exports_Schema.Natural
|
|
46960
|
+
});
|
|
46961
|
+
function repricingAnswer(response, decode5) {
|
|
46962
|
+
const status = response.status;
|
|
46963
|
+
if (status >= 200 && status < 300)
|
|
46964
|
+
return decode5(response).pipe(exports_Effect.mapError(() => new RepricingRefused({ status, message: "The server's reply was not understood." })));
|
|
46965
|
+
if (status >= 500 || status === 408 || status === 429)
|
|
46966
|
+
return exports_Effect.fail(new RepricingUnavailable({ message: `The server is temporarily unavailable (${status}).` }));
|
|
46967
|
+
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}).`));
|
|
46968
|
+
return exports_Effect.fail(new RepricingRefused({ status, message }));
|
|
46969
|
+
}
|
|
46970
|
+
function exchange(server, request3, decode5, timeout4) {
|
|
46971
|
+
return exports_Effect.gen(function* () {
|
|
46972
|
+
const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
|
|
46973
|
+
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({
|
|
46974
|
+
while: exports_Predicate.isTagged("RepricingUnavailable"),
|
|
46975
|
+
schedule: exports_Schedule.exponential("2 seconds"),
|
|
46976
|
+
times: 3
|
|
46977
|
+
}));
|
|
46978
|
+
});
|
|
46979
|
+
}
|
|
46980
|
+
var repricingStatus = exports_Effect.fn("Sync.repricingStatus")(function* (server, token, machineId, basis) {
|
|
46981
|
+
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");
|
|
46982
|
+
});
|
|
46983
|
+
var reprice = exports_Effect.fn("Sync.reprice")(function* (server, token, machineId, payload) {
|
|
46984
|
+
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);
|
|
46985
|
+
return yield* exchange(server, request3, exports_HttpClientResponse.schemaBodyJson(RepricingReceipt), "60 seconds");
|
|
46986
|
+
});
|
|
46987
|
+
|
|
46988
|
+
// packages/cli/src/reprice.ts
|
|
46989
|
+
var hour2 = 3600000;
|
|
46990
|
+
var isProvider = exports_Schema.is(Provider);
|
|
46991
|
+
var RepriceStep = exports_Data.taggedEnum();
|
|
46992
|
+
function repricePlan(status, scope3) {
|
|
46993
|
+
const floor = exports_DateTime.toEpochMillis(status.floor);
|
|
46994
|
+
return status.providers.flatMap((entry) => {
|
|
46995
|
+
const provider = entry.provider;
|
|
46996
|
+
if (!isProvider(provider) || !scope3.providers.has(provider) || entry.from === null)
|
|
46997
|
+
return [];
|
|
46998
|
+
const from = exports_DateTime.toEpochMillis(entry.from);
|
|
46999
|
+
const start = Math.ceil(Math.max(from, floor) / hour2) * hour2;
|
|
47000
|
+
if (start >= scope3.windowStart)
|
|
47001
|
+
return [];
|
|
47002
|
+
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));
|
|
47003
|
+
const staleBuckets = entry.staleBuckets;
|
|
47004
|
+
return [
|
|
47005
|
+
finished ? RepriceStep.Skip({ provider, from, staleBuckets }) : RepriceStep.Reprice({
|
|
47006
|
+
provider,
|
|
47007
|
+
from,
|
|
47008
|
+
range: { start, end: scope3.windowStart },
|
|
47009
|
+
staleBuckets
|
|
47010
|
+
})
|
|
47011
|
+
];
|
|
47012
|
+
});
|
|
47013
|
+
}
|
|
47014
|
+
var RepriceOutcome = exports_Data.taggedEnum();
|
|
47015
|
+
var repriceProvider = exports_Effect.fn("Sync.repriceProvider")(function* (run7, basis, step) {
|
|
47016
|
+
const { provider, from, staleBuckets } = step;
|
|
47017
|
+
let updated = 0;
|
|
47018
|
+
let unmatched = 0;
|
|
47019
|
+
let beforeFloor = 0;
|
|
47020
|
+
const failed = (message) => RepriceOutcome.Failed({ provider, from, message, updated, unmatched });
|
|
47021
|
+
const scanned = yield* run7.scan(provider, step.range).pipe(exports_Effect.result);
|
|
47022
|
+
if (exports_Result.isFailure(scanned))
|
|
47023
|
+
return failed(scanned.failure.message);
|
|
47024
|
+
const { buckets, coverage } = scanned.success;
|
|
47025
|
+
if (coverage.status === "failed")
|
|
47026
|
+
return failed("Some of its history could not be read.");
|
|
47027
|
+
if (coverage.status === "missing")
|
|
47028
|
+
return RepriceOutcome.NoHistory({ provider, from, staleBuckets });
|
|
47029
|
+
const { status, fetchedAt, source } = run7.payload.pricing;
|
|
47030
|
+
for (const chunk of repriceChunks(buckets)) {
|
|
47031
|
+
const payload = yield* RepricePayload.makeEffect({
|
|
47032
|
+
version: 1,
|
|
47033
|
+
clientVersion: run7.payload.clientVersion,
|
|
47034
|
+
pricing: { status, fetchedAt, source, basis },
|
|
47035
|
+
buckets: chunk
|
|
47036
|
+
}).pipe(exports_Effect.result);
|
|
47037
|
+
if (exports_Result.isFailure(payload))
|
|
47038
|
+
return failed("Its buckets do not satisfy the repricing contract.");
|
|
47039
|
+
const receipt = yield* reprice(run7.server, run7.token, run7.payload.machine.id, payload.success).pipe(exports_Effect.result);
|
|
47040
|
+
if (exports_Result.isFailure(receipt))
|
|
47041
|
+
return failed(receipt.failure.message);
|
|
47042
|
+
updated += receipt.success.updated;
|
|
47043
|
+
unmatched += receipt.success.unmatched;
|
|
47044
|
+
beforeFloor += receipt.success.beforeFloor;
|
|
47045
|
+
}
|
|
47046
|
+
return RepriceOutcome.Repriced({
|
|
47047
|
+
provider,
|
|
47048
|
+
from,
|
|
47049
|
+
staleBuckets,
|
|
47050
|
+
sent: buckets.length,
|
|
47051
|
+
updated,
|
|
47052
|
+
unmatched,
|
|
47053
|
+
beforeFloor
|
|
47054
|
+
});
|
|
47055
|
+
});
|
|
47056
|
+
var repriceStoredUsage = exports_Effect.fn("Sync.repriceStoredUsage")(function* (run7) {
|
|
47057
|
+
const basis = run7.payload.pricing.basis;
|
|
47058
|
+
if (basis === undefined)
|
|
47059
|
+
return [];
|
|
47060
|
+
const answer = yield* repricingStatus(run7.server, run7.token, run7.payload.machine.id, basis).pipe(exports_Effect.result);
|
|
47061
|
+
if (exports_Result.isFailure(answer))
|
|
47062
|
+
return [RepriceOutcome.Unanswered({ message: answer.failure.message })];
|
|
47063
|
+
const server = run7.server.origin;
|
|
47064
|
+
const completed = yield* loadRepricing(run7.directory);
|
|
47065
|
+
const steps = repricePlan(answer.success, {
|
|
47066
|
+
windowStart: Date.parse(run7.payload.window.start),
|
|
47067
|
+
providers: run7.providers,
|
|
47068
|
+
server,
|
|
47069
|
+
basis,
|
|
47070
|
+
completed
|
|
47071
|
+
});
|
|
47072
|
+
const outcomes = [];
|
|
47073
|
+
const finished = [];
|
|
47074
|
+
const coveredUntil = exports_DateTime.makeUnsafe(run7.payload.window.end);
|
|
47075
|
+
for (const step of steps) {
|
|
47076
|
+
const outcome = yield* RepriceStep.$match(step, {
|
|
47077
|
+
Skip: ({ provider, from, staleBuckets }) => exports_Effect.succeed(RepriceOutcome.Skipped({ provider, from, staleBuckets })),
|
|
47078
|
+
Reprice: (send) => repriceProvider(run7, basis, send)
|
|
47079
|
+
});
|
|
47080
|
+
outcomes.push(outcome);
|
|
47081
|
+
if (RepriceOutcome.$is("Repriced")(outcome))
|
|
47082
|
+
finished.push({
|
|
47083
|
+
server,
|
|
47084
|
+
provider: outcome.provider,
|
|
47085
|
+
basis,
|
|
47086
|
+
from: exports_DateTime.makeUnsafe(outcome.from),
|
|
47087
|
+
coveredUntil
|
|
47088
|
+
});
|
|
47089
|
+
}
|
|
47090
|
+
if (finished.length === 0)
|
|
47091
|
+
return outcomes;
|
|
47092
|
+
const kept = completed.filter((entry) => !finished.some((done4) => done4.server === entry.server && done4.provider === entry.provider));
|
|
47093
|
+
const saved = yield* saveRepricing(run7.directory, [...kept, ...finished]).pipe(exports_Effect.result);
|
|
47094
|
+
if (exports_Result.isFailure(saved))
|
|
47095
|
+
outcomes.push(RepriceOutcome.Unremembered({ message: saved.failure.message }));
|
|
47096
|
+
return outcomes;
|
|
47097
|
+
});
|
|
47098
|
+
|
|
45842
47099
|
// packages/cli/src/format.ts
|
|
45843
47100
|
function csvCell(value5) {
|
|
45844
47101
|
const text2 = value5 === null ? "" : String(value5);
|
|
@@ -45997,83 +47254,61 @@ function syncSummary(payload, request3, storedBuckets) {
|
|
|
45997
47254
|
].join(`
|
|
45998
47255
|
`);
|
|
45999
47256
|
}
|
|
46000
|
-
|
|
46001
|
-
|
|
46002
|
-
|
|
46003
|
-
|
|
46004
|
-
}
|
|
46005
|
-
|
|
46006
|
-
|
|
46007
|
-
|
|
46008
|
-
|
|
46009
|
-
|
|
46010
|
-
}) {
|
|
46011
|
-
|
|
46012
|
-
|
|
46013
|
-
|
|
46014
|
-
}
|
|
46015
|
-
|
|
46016
|
-
class SyncSuperseded extends exports_Schema.TaggedError()("SyncSuperseded", {
|
|
46017
|
-
message: exports_Schema.String
|
|
46018
|
-
}) {
|
|
46019
|
-
}
|
|
46020
|
-
|
|
46021
|
-
class SyncRejected extends exports_Schema.TaggedError()("SyncRejected", {
|
|
46022
|
-
status: exports_Schema.Number,
|
|
46023
|
-
message: exports_Schema.String
|
|
46024
|
-
}) {
|
|
47257
|
+
function unpricedModels(rows) {
|
|
47258
|
+
const counts = new Map;
|
|
47259
|
+
for (const row of rows)
|
|
47260
|
+
if (row.unpricedRecords > 0) {
|
|
47261
|
+
const name = `${terminalText(row.model)} (${row.provider}`;
|
|
47262
|
+
counts.set(name, (counts.get(name) ?? 0) + row.unpricedRecords);
|
|
47263
|
+
}
|
|
47264
|
+
if (counts.size === 0)
|
|
47265
|
+
return;
|
|
47266
|
+
const number4 = new Intl.NumberFormat("en-US");
|
|
47267
|
+
const ranked = [...counts].toSorted(([leftName, left], [rightName, right]) => right - left || leftName.localeCompare(rightName)).map(([name, records]) => `${name}, ${number4.format(records)} ${records === 1 ? "record" : "records"})`);
|
|
47268
|
+
const shown = ranked.slice(0, 5).join(", ");
|
|
47269
|
+
const more = ranked.length > 5 ? ` and ${ranked.length - 5} more` : "";
|
|
47270
|
+
return `Unpriced: ${shown}${more}. Configure their rates under "prices" to price them.`;
|
|
46025
47271
|
}
|
|
46026
|
-
|
|
46027
|
-
|
|
46028
|
-
staleAfterDays: exports_Schema.Number,
|
|
46029
|
-
from: exports_Schema.String,
|
|
46030
|
-
to: exports_Schema.String,
|
|
46031
|
-
machines: exports_Schema.Array(exports_Schema.Struct({ machineId: exports_Schema.String.check(exports_Schema.isUUID()) }))
|
|
46032
|
-
});
|
|
46033
|
-
function endpoint(server, path) {
|
|
46034
|
-
const base = new URL(server);
|
|
46035
|
-
base.pathname = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
|
|
46036
|
-
return new URL(path, base);
|
|
47272
|
+
function utcHour(instant) {
|
|
47273
|
+
return `${new Date(instant).toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
|
46037
47274
|
}
|
|
46038
|
-
|
|
46039
|
-
|
|
46040
|
-
const
|
|
46041
|
-
|
|
46042
|
-
|
|
46043
|
-
|
|
46044
|
-
|
|
46045
|
-
|
|
46046
|
-
|
|
46047
|
-
|
|
46048
|
-
|
|
46049
|
-
|
|
46050
|
-
|
|
46051
|
-
|
|
46052
|
-
|
|
46053
|
-
|
|
46054
|
-
|
|
46055
|
-
|
|
46056
|
-
|
|
46057
|
-
|
|
46058
|
-
})
|
|
46059
|
-
|
|
46060
|
-
|
|
46061
|
-
|
|
46062
|
-
|
|
46063
|
-
|
|
46064
|
-
|
|
46065
|
-
|
|
46066
|
-
|
|
46067
|
-
|
|
46068
|
-
})
|
|
46069
|
-
|
|
46070
|
-
|
|
46071
|
-
|
|
46072
|
-
|
|
46073
|
-
message: `Could not ask ${url.origin} whether this machine has uploaded before.`
|
|
47275
|
+
function repriceLine(outcome) {
|
|
47276
|
+
const number4 = new Intl.NumberFormat("en-US");
|
|
47277
|
+
const buckets = (count2) => `${number4.format(count2)} ${count2 === 1 ? "bucket" : "buckets"}`;
|
|
47278
|
+
return RepriceOutcome.$match(outcome, {
|
|
47279
|
+
Repriced: ({ provider, from, staleBuckets, sent, updated, unmatched, beforeFloor }) => ({
|
|
47280
|
+
text: [
|
|
47281
|
+
`Repriced ${provider} from ${utcHour(from)}`,
|
|
47282
|
+
`${buckets(staleBuckets)} stored on an older pricing basis`,
|
|
47283
|
+
`sent ${number4.format(sent)}`,
|
|
47284
|
+
`${number4.format(updated)} updated`,
|
|
47285
|
+
`${number4.format(unmatched)} unmatched`,
|
|
47286
|
+
...beforeFloor > 0 ? [`${number4.format(beforeFloor)} before the server's floor`] : []
|
|
47287
|
+
].join(" · "),
|
|
47288
|
+
problem: false
|
|
47289
|
+
}),
|
|
47290
|
+
Skipped: ({ provider, from, staleBuckets }) => ({
|
|
47291
|
+
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.`,
|
|
47292
|
+
problem: false
|
|
47293
|
+
}),
|
|
47294
|
+
NoHistory: ({ provider, from, staleBuckets }) => ({
|
|
47295
|
+
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.`,
|
|
47296
|
+
problem: false
|
|
47297
|
+
}),
|
|
47298
|
+
Failed: ({ provider, from, message, updated, unmatched }) => ({
|
|
47299
|
+
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.`,
|
|
47300
|
+
problem: true
|
|
47301
|
+
}),
|
|
47302
|
+
Unanswered: ({ message }) => ({
|
|
47303
|
+
text: `Could not ask the server what to reprice: ${message} The next sync asks again.`,
|
|
47304
|
+
problem: true
|
|
47305
|
+
}),
|
|
47306
|
+
Unremembered: ({ message }) => ({
|
|
47307
|
+
text: `${message} The next sync sends its reprices again.`,
|
|
47308
|
+
problem: true
|
|
47309
|
+
})
|
|
46074
47310
|
});
|
|
46075
|
-
|
|
46076
|
-
});
|
|
47311
|
+
}
|
|
46077
47312
|
|
|
46078
47313
|
// packages/cli/src/main.ts
|
|
46079
47314
|
class CliError2 extends exports_Schema.TaggedError()("CliError", { message: exports_Schema.String }) {
|
|
@@ -46122,6 +47357,7 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
|
|
|
46122
47357
|
const grokHome = yield* exports_Config.String("GROK_HOME").pipe(exports_Config.withDefault(path.join(home, ".grok")));
|
|
46123
47358
|
const copilotHome = yield* exports_Config.String("COPILOT_HOME").pipe(exports_Config.withDefault(path.join(home, ".copilot")));
|
|
46124
47359
|
const copilotFile = yield* exports_Config.String("COPILOT_OTEL_FILE_EXPORTER_PATH").pipe(exports_Config.option);
|
|
47360
|
+
const copilotSessions = path.join(expand(copilotHome), "session-state");
|
|
46125
47361
|
const piHome = yield* exports_Config.String("PI_CODING_AGENT_DIR").pipe(exports_Config.withDefault(path.join(home, ".pi", "agent")));
|
|
46126
47362
|
const piSessions = yield* exports_Config.String("PI_CODING_AGENT_SESSION_DIR").pipe(exports_Config.option);
|
|
46127
47363
|
const opencodeData = path.join(exports_Option.getOrElse(yield* dataHome, () => path.join(home, ".local", "share")), "opencode");
|
|
@@ -46131,6 +47367,7 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
|
|
|
46131
47367
|
{ provider: "codex", path: path.join(expand(codexHome), "archived_sessions") },
|
|
46132
47368
|
{ provider: "claude", path: path.join(expand(claudeHome), "projects") },
|
|
46133
47369
|
{ provider: "grok", path: path.join(expand(grokHome), "sessions") },
|
|
47370
|
+
...(yield* fs.exists(copilotSessions)) ? [{ provider: "copilot", path: copilotSessions }] : [],
|
|
46134
47371
|
...(yield* copilotSources(path.join(expand(copilotHome), "otel"), exports_Option.map(copilotFile, (value5) => expand(value5)))).map((source) => ({ provider: "copilot", path: source })),
|
|
46135
47372
|
{
|
|
46136
47373
|
provider: "pi",
|
|
@@ -46171,13 +47408,8 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
|
|
|
46171
47408
|
paths: mapping.paths.map((prefix3) => expand(prefix3, path.dirname(configFile)))
|
|
46172
47409
|
}));
|
|
46173
47410
|
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
|
-
});
|
|
47411
|
+
const basePrices = yield* loadPrices(path.join(expand(cacheRoot), "token-ledger", "prices-v2.json"), flags.offline);
|
|
47412
|
+
const pricing = configuredPricing(basePrices, configuration.prices);
|
|
46181
47413
|
if (pricing.status === "unavailable")
|
|
46182
47414
|
yield* exports_Console.error("Pricing unavailable: unknown rates remain unpriced. Configure prices or rerun online.");
|
|
46183
47415
|
const request3 = yield* ReportRequest.makeEffect({
|
|
@@ -46212,6 +47444,9 @@ var report = exports_Command.make("report", {
|
|
|
46212
47444
|
if (source.status !== "ok" || source.warnings.length > 0)
|
|
46213
47445
|
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
47446
|
}
|
|
47447
|
+
const unpriced = unpricedModels(result6.rows);
|
|
47448
|
+
if (unpriced !== undefined)
|
|
47449
|
+
yield* exports_Console.error(unpriced);
|
|
46215
47450
|
if (flags.strict && (result6.coverage.some((entry) => entry.status !== "ok") || result6.rows.some((row) => row.unpricedRecords > 0)))
|
|
46216
47451
|
process.exitCode = 2;
|
|
46217
47452
|
})).pipe(exports_Command.withDescription("Report local token consumption and API-equivalent cost by project"));
|
|
@@ -46260,10 +47495,20 @@ var sync6 = exports_Command.make("sync", {
|
|
|
46260
47495
|
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
47496
|
if (flags.dryRun) {
|
|
46262
47497
|
yield* exports_Console.log(JSON.stringify(first.payload, null, 2));
|
|
47498
|
+
const unpriced2 = unpricedModels(first.payload.buckets);
|
|
47499
|
+
if (unpriced2 !== undefined)
|
|
47500
|
+
yield* exports_Console.error(unpriced2);
|
|
46263
47501
|
if (flags.strict && incomplete)
|
|
46264
47502
|
process.exitCode = 2;
|
|
46265
47503
|
return;
|
|
46266
47504
|
}
|
|
47505
|
+
yield* retimeDailySchedule(directory).pipe(exports_Effect.matchEffect({
|
|
47506
|
+
onSuccess: exports_Option.match({
|
|
47507
|
+
onNone: () => exports_Effect.void,
|
|
47508
|
+
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.`)
|
|
47509
|
+
}),
|
|
47510
|
+
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.`)
|
|
47511
|
+
}));
|
|
46267
47512
|
const refused = exports_Effect.gen(function* () {
|
|
46268
47513
|
yield* exports_Console.error("Not syncing: coverage is incomplete or usage is unpriced (--strict).");
|
|
46269
47514
|
process.exitCode = 2;
|
|
@@ -46300,7 +47545,20 @@ var sync6 = exports_Command.make("sync", {
|
|
|
46300
47545
|
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
47546
|
return;
|
|
46302
47547
|
}
|
|
47548
|
+
const unpriced = unpricedModels(sent.payload.buckets);
|
|
47549
|
+
if (unpriced !== undefined)
|
|
47550
|
+
yield* exports_Console.error(unpriced);
|
|
46303
47551
|
yield* exports_Console.log(syncSummary(sent.payload, { ...request3, since: sent.since }, outcome.success));
|
|
47552
|
+
const repriced = yield* repriceStoredUsage({
|
|
47553
|
+
server: server.value,
|
|
47554
|
+
token: token.value,
|
|
47555
|
+
payload: sent.payload,
|
|
47556
|
+
providers: new Set(request3.sources.map((source) => source.provider)),
|
|
47557
|
+
directory,
|
|
47558
|
+
scan: (provider, range3) => ledger.repriceBuckets(request3, provider, range3)
|
|
47559
|
+
});
|
|
47560
|
+
for (const { text: text2, problem } of repriced.map(repriceLine))
|
|
47561
|
+
yield* problem ? exports_Console.error(text2) : exports_Console.log(text2);
|
|
46304
47562
|
})).pipe(exports_Command.withDescription("Upload hourly usage buckets from this machine to toki2; the server replaces the window"));
|
|
46305
47563
|
var interactive = (prompt) => exports_Prompt.run(prompt).pipe(exports_Effect.mapError(() => new CliError2({
|
|
46306
47564
|
message: "Nothing was saved. Without a terminal, pass --server and set TOKI_API_TOKEN."
|
|
@@ -46325,7 +47583,7 @@ var login = exports_Command.make("login", {
|
|
|
46325
47583
|
Next: token-ledger sync --dry-run, then token-ledger schedule install.`);
|
|
46326
47584
|
})).pipe(exports_Command.withDescription("Save the toki2 server and API token in sync.json for sync and scheduled syncs"));
|
|
46327
47585
|
var scheduleInstall = exports_Command.make("install", {
|
|
46328
|
-
every: exports_Flag.ChoiceWithValue("every", intervals).pipe(exports_Flag.withDefault(
|
|
47586
|
+
every: exports_Flag.ChoiceWithValue("every", intervals).pipe(exports_Flag.withDefault(defaultInterval), exports_Flag.withDescription(`Time between syncs; defaults to ${defaultInterval}h`)),
|
|
46329
47587
|
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
47588
|
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
47589
|
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 +47628,7 @@ var scheduleInstall = exports_Command.make("install", {
|
|
|
46370
47628
|
message: "No saved server and API token. Run token-ledger login first: a scheduled sync cannot read --token or your shell's environment."
|
|
46371
47629
|
});
|
|
46372
47630
|
yield* perform(actions);
|
|
47631
|
+
yield* settleSchedule(directory).pipe(exports_Effect.ignore);
|
|
46373
47632
|
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
47633
|
})).pipe(exports_Command.withDescription("Install or replace the scheduled sync; it needs the server and token saved by login"));
|
|
46375
47634
|
var scheduleStatus = exports_Command.make("status", {}, exports_Effect.fn("CLI.scheduleStatus")(function* () {
|