@ponbac/token-ledger 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +167 -26
- package/dist/main.js +1612 -266
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -32733,7 +32733,7 @@ var readBillingHints = exports_Effect.fn("BillingHints.read")(function* (locatio
|
|
|
32733
32733
|
});
|
|
32734
32734
|
|
|
32735
32735
|
// packages/core/src/model.ts
|
|
32736
|
-
var Provider = exports_Schema.Literals(["codex", "claude", "grok", "copilot", "pi"]);
|
|
32736
|
+
var Provider = exports_Schema.Literals(["codex", "claude", "grok", "copilot", "pi", "opencode"]);
|
|
32737
32737
|
var BillingProvider = exports_Schema.Literals(["codex", "claude", "grok", "copilot"]);
|
|
32738
32738
|
var Tokens = exports_Schema.Struct({
|
|
32739
32739
|
input: exports_Schema.Natural,
|
|
@@ -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]+):((?!\/\/).+)$/;
|
|
@@ -34478,6 +35109,7 @@ var projectResolver = exports_Effect.fn("Projects.resolver")(function* (mappings
|
|
|
34478
35109
|
var empty14 = {
|
|
34479
35110
|
records: [],
|
|
34480
35111
|
inherited: [],
|
|
35112
|
+
deferred: [],
|
|
34481
35113
|
hints: [],
|
|
34482
35114
|
malformed: 0,
|
|
34483
35115
|
skipped: 0,
|
|
@@ -34507,10 +35139,12 @@ var Assistant = exports_Schema.Struct({
|
|
|
34507
35139
|
input_tokens: exports_Schema.Natural,
|
|
34508
35140
|
output_tokens: exports_Schema.Natural,
|
|
34509
35141
|
cache_read_input_tokens: exports_Schema.optionalKey(exports_Schema.Natural),
|
|
34510
|
-
cache_creation_input_tokens: exports_Schema.optionalKey(exports_Schema.Natural)
|
|
35142
|
+
cache_creation_input_tokens: exports_Schema.optionalKey(exports_Schema.Natural),
|
|
35143
|
+
cache_creation: exports_Schema.optionalKey(exports_Schema.Unknown)
|
|
34511
35144
|
})
|
|
34512
35145
|
})
|
|
34513
35146
|
});
|
|
35147
|
+
var decodeCacheCreation = exports_Schema.decodeUnknownOption(exports_Schema.Struct({ ephemeral_1h_input_tokens: exports_Schema.optionalKey(exports_Schema.Natural) }));
|
|
34514
35148
|
function claudeParser(file2) {
|
|
34515
35149
|
return {
|
|
34516
35150
|
parse(line, lineNumber) {
|
|
@@ -34526,25 +35160,26 @@ function claudeParser(file2) {
|
|
|
34526
35160
|
const usage = event.message.usage;
|
|
34527
35161
|
const session = event.sessionId ?? file2;
|
|
34528
35162
|
const id2 = event.message.id === undefined && event.requestId === undefined ? `${file2}:${lineNumber}` : `${event.message.id ?? ""}:${event.requestId ?? ""}`;
|
|
35163
|
+
const cacheWrite = usage.cache_creation_input_tokens ?? 0;
|
|
35164
|
+
const oneHour = Math.min(exports_Option.getOrNull(decodeCacheCreation(usage.cache_creation))?.ephemeral_1h_input_tokens ?? 0, cacheWrite);
|
|
35165
|
+
const record3 = {
|
|
35166
|
+
provider: "claude",
|
|
35167
|
+
id: id2,
|
|
35168
|
+
session,
|
|
35169
|
+
timestamp: ms,
|
|
35170
|
+
model: event.message.model,
|
|
35171
|
+
cwd: event.cwd ?? null,
|
|
35172
|
+
repository: null,
|
|
35173
|
+
tokens: {
|
|
35174
|
+
input: usage.input_tokens,
|
|
35175
|
+
output: usage.output_tokens,
|
|
35176
|
+
cacheRead: usage.cache_read_input_tokens ?? 0,
|
|
35177
|
+
cacheWrite
|
|
35178
|
+
}
|
|
35179
|
+
};
|
|
34529
35180
|
return {
|
|
34530
35181
|
...empty14,
|
|
34531
|
-
records: [
|
|
34532
|
-
{
|
|
34533
|
-
provider: "claude",
|
|
34534
|
-
id: id2,
|
|
34535
|
-
session,
|
|
34536
|
-
timestamp: ms,
|
|
34537
|
-
model: event.message.model,
|
|
34538
|
-
cwd: event.cwd ?? null,
|
|
34539
|
-
repository: null,
|
|
34540
|
-
tokens: {
|
|
34541
|
-
input: usage.input_tokens,
|
|
34542
|
-
output: usage.output_tokens,
|
|
34543
|
-
cacheRead: usage.cache_read_input_tokens ?? 0,
|
|
34544
|
-
cacheWrite: usage.cache_creation_input_tokens ?? 0
|
|
34545
|
-
}
|
|
34546
|
-
}
|
|
34547
|
-
],
|
|
35182
|
+
records: [oneHour > 0 ? { ...record3, cacheWrite1h: oneHour } : record3],
|
|
34548
35183
|
warnings: event.message.id === undefined && event.requestId === undefined ? ["Some Claude records lack stable IDs; copied histories may overlap."] : []
|
|
34549
35184
|
};
|
|
34550
35185
|
}
|
|
@@ -34947,6 +35582,7 @@ function grokParser(file2) {
|
|
|
34947
35582
|
if (cacheRead + cacheWrite > count2.inputTokens)
|
|
34948
35583
|
return skipped;
|
|
34949
35584
|
records.push({
|
|
35585
|
+
aggregate: true,
|
|
34950
35586
|
provider: "grok",
|
|
34951
35587
|
id: `${session}:${promptId ?? `${file2}:${lineNumber}`}:${model}`,
|
|
34952
35588
|
session,
|
|
@@ -34976,6 +35612,208 @@ function grokParser(file2) {
|
|
|
34976
35612
|
};
|
|
34977
35613
|
}
|
|
34978
35614
|
|
|
35615
|
+
// packages/core/src/providers/opencode-db.ts
|
|
35616
|
+
class OpencodeDatabaseError extends exports_Schema.TaggedError()("OpencodeDatabaseError", { message: exports_Schema.String }) {
|
|
35617
|
+
}
|
|
35618
|
+
var opencodeDatabaseName = /^opencode(?:-[A-Za-z0-9._-]+)?\.db$/;
|
|
35619
|
+
var Names = exports_Schema.Array(exports_Schema.Struct({ name: exports_Schema.String }));
|
|
35620
|
+
var Lines = exports_Schema.Array(exports_Schema.Struct({ line: exports_Schema.String }));
|
|
35621
|
+
var databaseError2 = () => new OpencodeDatabaseError({ message: "Cannot read the OpenCode database." });
|
|
35622
|
+
var tokens = (data) => `json_object(
|
|
35623
|
+
'input', json_extract(${data}, '$.tokens.input'),
|
|
35624
|
+
'output', json_extract(${data}, '$.tokens.output'),
|
|
35625
|
+
'reasoning', json_extract(${data}, '$.tokens.reasoning'),
|
|
35626
|
+
'cache', json_object(
|
|
35627
|
+
'read', json_extract(${data}, '$.tokens.cache.read'),
|
|
35628
|
+
'write', json_extract(${data}, '$.tokens.cache.write')))`;
|
|
35629
|
+
var opencodeDatabaseLines = exports_Effect.fn("Opencode.readDatabase")(function* (file2, since, until) {
|
|
35630
|
+
return yield* exports_Effect.gen(function* () {
|
|
35631
|
+
const { DatabaseSync } = yield* exports_Effect.tryPromise({
|
|
35632
|
+
try: () => import("node:sqlite"),
|
|
35633
|
+
catch: databaseError2
|
|
35634
|
+
});
|
|
35635
|
+
const db = yield* exports_Effect.acquireRelease(exports_Effect.try({
|
|
35636
|
+
try: () => new DatabaseSync(file2, { readOnly: true, timeout: 5000 }),
|
|
35637
|
+
catch: databaseError2
|
|
35638
|
+
}), (connection) => exports_Effect.sync(() => connection.close()));
|
|
35639
|
+
const columns = yield* exports_Effect.try({
|
|
35640
|
+
try: () => db.prepare("SELECT t.name || '.' || c.name AS name FROM sqlite_master t, pragma_table_info(t.name) c WHERE t.type = 'table'").all(),
|
|
35641
|
+
catch: databaseError2
|
|
35642
|
+
}).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(Names)), exports_Effect.mapError(databaseError2), exports_Effect.map((rows2) => new Set(rows2.map((row) => row.name))));
|
|
35643
|
+
const has5 = (table2, ...names) => names.every((name) => columns.has(`${table2}.${name}`));
|
|
35644
|
+
const messages = has5("message", "id", "session_id", "time_created", "data");
|
|
35645
|
+
const v2 = has5("session_message", "id", "session_id", "type", "time_created", "data");
|
|
35646
|
+
if (!messages && !v2)
|
|
35647
|
+
return yield* new OpencodeDatabaseError({
|
|
35648
|
+
message: "The OpenCode database has no message table."
|
|
35649
|
+
});
|
|
35650
|
+
const sessions = (alias) => (alias === "v" ? ["session_v2", "session"] : ["session", "session_v2"]).filter((table2) => has5(table2, "id", "directory", "time_created"));
|
|
35651
|
+
const joins = (alias) => sessions(alias).map((table2, index2) => `LEFT JOIN ${table2} s${index2} ON s${index2}.id = ${alias}.session_id`).join(" ");
|
|
35652
|
+
const sessionField = (alias, field) => `COALESCE(${[...sessions(alias).map((_, index2) => `s${index2}.${field}`), "NULL"].join(", ")})`;
|
|
35653
|
+
const line = (alias, role, provider, model, cwd) => `json_object(
|
|
35654
|
+
'id', ${alias}.id,
|
|
35655
|
+
'sessionID', ${alias}.session_id,
|
|
35656
|
+
'role', ${role},
|
|
35657
|
+
'providerID', json_extract(${alias}.data, '${provider}'),
|
|
35658
|
+
'modelID', json_extract(${alias}.data, '${model}'),
|
|
35659
|
+
'time', json_object('created', ${alias}.time_created),
|
|
35660
|
+
'cost', json_extract(${alias}.data, '$.cost'),
|
|
35661
|
+
'tokens', ${tokens(`${alias}.data`)},
|
|
35662
|
+
'path', json_object('cwd', ${cwd}),
|
|
35663
|
+
'directory', ${sessionField(alias, "directory")},
|
|
35664
|
+
'forked', json(CASE WHEN ${alias}.time_created < ${sessionField(alias, "time_created")} THEN 'true' ELSE 'false' END)
|
|
35665
|
+
) AS line, ${alias}.time_created AS created, ${alias}.id AS id`;
|
|
35666
|
+
const queries = [
|
|
35667
|
+
...messages ? [
|
|
35668
|
+
`SELECT ${line("m", "json_extract(m.data, '$.role')", "$.providerID", "$.modelID", "json_extract(m.data, '$.path.cwd')")}
|
|
35669
|
+
FROM message m ${joins("m")}
|
|
35670
|
+
WHERE m.time_created >= ? AND m.time_created < ?
|
|
35671
|
+
AND (json_extract(m.data, '$.role') = 'assistant' OR json_type(m.data, '$.tokens') IS NOT NULL)`
|
|
35672
|
+
] : [],
|
|
35673
|
+
...v2 ? [
|
|
35674
|
+
`SELECT ${line("v", "v.type", "$.model.providerID", "$.model.id", "NULL")}
|
|
35675
|
+
FROM session_message v ${joins("v")}
|
|
35676
|
+
WHERE v.time_created >= ? AND v.time_created < ?
|
|
35677
|
+
AND (v.type = 'assistant' OR json_type(v.data, '$.tokens') IS NOT NULL)
|
|
35678
|
+
${messages ? "AND NOT EXISTS (SELECT 1 FROM message m WHERE m.id = v.id)" : ""}`
|
|
35679
|
+
] : []
|
|
35680
|
+
];
|
|
35681
|
+
const rows = yield* exports_Effect.try({
|
|
35682
|
+
try: () => db.prepare(`${queries.join(" UNION ALL ")} ORDER BY created, id`).all(...queries.flatMap(() => [since, until])),
|
|
35683
|
+
catch: databaseError2
|
|
35684
|
+
});
|
|
35685
|
+
const decoded = yield* exports_Schema.decodeUnknownEffect(Lines)(rows).pipe(exports_Effect.mapError(databaseError2));
|
|
35686
|
+
return decoded.map((row) => row.line);
|
|
35687
|
+
}).pipe(exports_Effect.scoped);
|
|
35688
|
+
});
|
|
35689
|
+
|
|
35690
|
+
// packages/core/src/providers/opencode.ts
|
|
35691
|
+
var decodeCarrier = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
|
|
35692
|
+
role: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.String)),
|
|
35693
|
+
tokens: exports_Schema.optionalKey(exports_Schema.Unknown)
|
|
35694
|
+
}));
|
|
35695
|
+
var Count = exports_Schema.Natural;
|
|
35696
|
+
var unattributedModel = "unknown";
|
|
35697
|
+
var decodeSession = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
|
|
35698
|
+
id: exports_Schema.NonEmptyString,
|
|
35699
|
+
time: exports_Schema.Struct({ created: exports_Schema.Number.check(exports_Schema.isFinite()) })
|
|
35700
|
+
}));
|
|
35701
|
+
var decodeMessage = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
|
|
35702
|
+
id: exports_Schema.NonEmptyString,
|
|
35703
|
+
sessionID: exports_Schema.NonEmptyString,
|
|
35704
|
+
providerID: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.NonEmptyString)),
|
|
35705
|
+
modelID: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.NonEmptyString)),
|
|
35706
|
+
time: exports_Schema.Struct({ created: exports_Schema.Number.check(exports_Schema.isFinite()) }),
|
|
35707
|
+
tokens: exports_Schema.Struct({
|
|
35708
|
+
input: Count,
|
|
35709
|
+
output: Count,
|
|
35710
|
+
reasoning: Count,
|
|
35711
|
+
cache: exports_Schema.Struct({ read: Count, write: Count })
|
|
35712
|
+
}),
|
|
35713
|
+
cost: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.Number.check(exports_Schema.isFinite(), exports_Schema.isGreaterThanOrEqualTo(0)))),
|
|
35714
|
+
path: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.Struct({ cwd: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.String)) }))),
|
|
35715
|
+
directory: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.String)),
|
|
35716
|
+
forked: exports_Schema.optionalKey(exports_Schema.Boolean)
|
|
35717
|
+
}));
|
|
35718
|
+
function payer(providerID, cost) {
|
|
35719
|
+
if (providerID === "github-copilot")
|
|
35720
|
+
return "copilot";
|
|
35721
|
+
if (providerID === "openai" && cost === 0)
|
|
35722
|
+
return "codex";
|
|
35723
|
+
return;
|
|
35724
|
+
}
|
|
35725
|
+
function opencodeHistory(nativePath) {
|
|
35726
|
+
const sessions = new Map;
|
|
35727
|
+
const originals = new Map;
|
|
35728
|
+
const copied = new Set;
|
|
35729
|
+
const pending = new Map;
|
|
35730
|
+
const native = (value5) => value5 === undefined || value5 === null || value5 === "" ? null : nativePath(value5);
|
|
35731
|
+
const sessionParser = {
|
|
35732
|
+
parse(line) {
|
|
35733
|
+
const raw2 = exports_Option.getOrNull(decodeJson(line));
|
|
35734
|
+
const session = raw2 === null ? null : exports_Option.getOrNull(decodeSession(raw2));
|
|
35735
|
+
if (session === null)
|
|
35736
|
+
return malformed;
|
|
35737
|
+
sessions.set(session.id, session.time.created);
|
|
35738
|
+
return empty14;
|
|
35739
|
+
}
|
|
35740
|
+
};
|
|
35741
|
+
const messageParser = {
|
|
35742
|
+
parse(line) {
|
|
35743
|
+
const raw2 = exports_Option.getOrNull(decodeJson(line));
|
|
35744
|
+
if (raw2 === null)
|
|
35745
|
+
return malformed;
|
|
35746
|
+
const carrier = exports_Option.getOrNull(decodeCarrier(raw2));
|
|
35747
|
+
if (carrier === null)
|
|
35748
|
+
return malformed;
|
|
35749
|
+
const assistant = carrier.role === "assistant";
|
|
35750
|
+
if (carrier.tokens === undefined || carrier.tokens === null)
|
|
35751
|
+
return assistant ? skipped : empty14;
|
|
35752
|
+
if (!assistant && carrier.role !== "compaction")
|
|
35753
|
+
return skipped;
|
|
35754
|
+
const message = exports_Option.getOrNull(decodeMessage(raw2));
|
|
35755
|
+
if (message === null || assistant && (!message.providerID || !message.modelID))
|
|
35756
|
+
return skipped;
|
|
35757
|
+
const { tokens: tokens2 } = message;
|
|
35758
|
+
const counts = {
|
|
35759
|
+
input: tokens2.input,
|
|
35760
|
+
cacheRead: tokens2.cache.read,
|
|
35761
|
+
cacheWrite: tokens2.cache.write,
|
|
35762
|
+
output: tokens2.output + tokens2.reasoning
|
|
35763
|
+
};
|
|
35764
|
+
const billingProvider = totalTokens(counts) > 0 ? payer(message.providerID, message.cost) : undefined;
|
|
35765
|
+
const own = {
|
|
35766
|
+
provider: "opencode",
|
|
35767
|
+
id: message.id,
|
|
35768
|
+
session: message.sessionID,
|
|
35769
|
+
timestamp: message.time.created,
|
|
35770
|
+
model: message.modelID ?? unattributedModel,
|
|
35771
|
+
cwd: native(message.path?.cwd) ?? native(message.directory),
|
|
35772
|
+
repository: null,
|
|
35773
|
+
tokens: counts
|
|
35774
|
+
};
|
|
35775
|
+
const record3 = billingProvider === undefined ? own : { ...own, billingProvider };
|
|
35776
|
+
const copyId = `fork:${JSON.stringify([
|
|
35777
|
+
message.time.created,
|
|
35778
|
+
message.providerID,
|
|
35779
|
+
message.modelID,
|
|
35780
|
+
tokens2.input,
|
|
35781
|
+
tokens2.output,
|
|
35782
|
+
tokens2.reasoning,
|
|
35783
|
+
tokens2.cache.read,
|
|
35784
|
+
tokens2.cache.write
|
|
35785
|
+
])}`;
|
|
35786
|
+
const warnings = message.modelID === undefined || message.modelID === null ? [
|
|
35787
|
+
"OpenCode compactions that failed name no model; these tokens remain unpriced unless an explicit rate is supplied."
|
|
35788
|
+
] : [];
|
|
35789
|
+
if (message.forked === undefined) {
|
|
35790
|
+
pending.set(record3, copyId);
|
|
35791
|
+
return { ...empty14, deferred: [record3], warnings };
|
|
35792
|
+
}
|
|
35793
|
+
if (message.forked) {
|
|
35794
|
+
copied.add(message.id);
|
|
35795
|
+
return { ...empty14, inherited: [{ ...record3, id: copyId }], warnings };
|
|
35796
|
+
}
|
|
35797
|
+
if (!originals.has(copyId))
|
|
35798
|
+
originals.set(copyId, message.id);
|
|
35799
|
+
return { ...empty14, records: [record3], warnings };
|
|
35800
|
+
}
|
|
35801
|
+
};
|
|
35802
|
+
return {
|
|
35803
|
+
parser: (file2) => file2 === "session" ? sessionParser : messageParser,
|
|
35804
|
+
classify: (record3) => {
|
|
35805
|
+
const copyId = pending.get(record3) ?? record3.id;
|
|
35806
|
+
const started = sessions.get(record3.session);
|
|
35807
|
+
if (copied.has(record3.id) || started !== undefined && record3.timestamp < started)
|
|
35808
|
+
return { record: { ...record3, id: copyId }, copy: true };
|
|
35809
|
+
if (!originals.has(copyId))
|
|
35810
|
+
originals.set(copyId, record3.id);
|
|
35811
|
+
return { record: record3, copy: false };
|
|
35812
|
+
},
|
|
35813
|
+
settle: (record3) => record3.provider === "opencode" ? { ...record3, id: originals.get(record3.id) ?? record3.id } : record3
|
|
35814
|
+
};
|
|
35815
|
+
}
|
|
35816
|
+
|
|
34979
35817
|
// packages/core/src/providers/pi.ts
|
|
34980
35818
|
var decodeKind = exports_Schema.decodeUnknownOption(exports_Schema.Struct({ type: exports_Schema.String }));
|
|
34981
35819
|
var decodeHeader = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
|
|
@@ -34985,7 +35823,7 @@ var decodeHeader = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
|
|
|
34985
35823
|
parentSession: exports_Schema.optionalKey(exports_Schema.String)
|
|
34986
35824
|
}));
|
|
34987
35825
|
var decodeWrapper = exports_Schema.decodeUnknownOption(exports_Schema.Struct({ message: exports_Schema.Unknown }));
|
|
34988
|
-
var
|
|
35826
|
+
var decodeCarrier2 = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
|
|
34989
35827
|
role: exports_Schema.optionalKey(exports_Schema.String),
|
|
34990
35828
|
usage: exports_Schema.optionalKey(exports_Schema.Unknown)
|
|
34991
35829
|
}));
|
|
@@ -35001,8 +35839,9 @@ var decodeCounts = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
|
|
|
35001
35839
|
cacheRead: exports_Schema.Natural,
|
|
35002
35840
|
cacheWrite: exports_Schema.Natural
|
|
35003
35841
|
}));
|
|
35004
|
-
var
|
|
35842
|
+
var unattributedModel2 = "unknown";
|
|
35005
35843
|
var chatGptSignIn = "openai-codex";
|
|
35844
|
+
var copilotSignIn = "github-copilot";
|
|
35006
35845
|
function piParser(file2) {
|
|
35007
35846
|
let session = file2;
|
|
35008
35847
|
let cwd = null;
|
|
@@ -35027,7 +35866,7 @@ function piParser(file2) {
|
|
|
35027
35866
|
return empty14;
|
|
35028
35867
|
}
|
|
35029
35868
|
const wrapper = type3 === "message" ? exports_Option.getOrNull(decodeWrapper(raw2)) : { message: raw2 };
|
|
35030
|
-
const carrier = wrapper === null ? null : exports_Option.getOrNull(
|
|
35869
|
+
const carrier = wrapper === null ? null : exports_Option.getOrNull(decodeCarrier2(wrapper.message));
|
|
35031
35870
|
if (wrapper === null || carrier === null)
|
|
35032
35871
|
return type3 === "message" ? malformed : empty14;
|
|
35033
35872
|
const assistant = type3 === "message" && carrier.role === "assistant";
|
|
@@ -35045,16 +35884,17 @@ function piParser(file2) {
|
|
|
35045
35884
|
if (stamp === null || names === null || count2 === null || ms === null)
|
|
35046
35885
|
return skipped;
|
|
35047
35886
|
const model = attributed ? names.responseModel ?? names.model : undefined;
|
|
35048
|
-
const
|
|
35887
|
+
const own = {
|
|
35049
35888
|
provider: "pi",
|
|
35050
35889
|
id: stamp.id === undefined ? `${file2}:${lineNumber}` : `${stamp.id}:${stamp.timestamp}`,
|
|
35051
35890
|
session,
|
|
35052
35891
|
timestamp: ms,
|
|
35053
|
-
model: model ??
|
|
35892
|
+
model: model ?? unattributedModel2,
|
|
35054
35893
|
cwd,
|
|
35055
35894
|
repository: null,
|
|
35056
35895
|
tokens: count2
|
|
35057
35896
|
};
|
|
35897
|
+
const record3 = attributed && names.provider === copilotSignIn && totalTokens(count2) > 0 ? { ...own, billingProvider: "copilot" } : type3 === "message" && carrier.role === "toolResult" ? { ...own, aggregate: true } : own;
|
|
35058
35898
|
const copied = forked !== null && ms < forked;
|
|
35059
35899
|
return {
|
|
35060
35900
|
...empty14,
|
|
@@ -35074,7 +35914,7 @@ function piParser(file2) {
|
|
|
35074
35914
|
}
|
|
35075
35915
|
|
|
35076
35916
|
// packages/core/src/sync.ts
|
|
35077
|
-
import { createHash as
|
|
35917
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
35078
35918
|
var hour = 3600000;
|
|
35079
35919
|
var UtcInstant = exports_Schema.String.check(exports_Schema.isPattern(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/), exports_Schema.makeFilter((s) => {
|
|
35080
35920
|
const ms = Date.parse(s);
|
|
@@ -35148,25 +35988,62 @@ var SyncPayload = exports_Schema.Struct({
|
|
|
35148
35988
|
pricing: exports_Schema.Struct({
|
|
35149
35989
|
status: PriceBook.fields.status,
|
|
35150
35990
|
fetchedAt: exports_Schema.NullOr(UtcInstant),
|
|
35151
|
-
source: Text
|
|
35991
|
+
source: Text,
|
|
35992
|
+
basis: exports_Schema.optionalKey(PricingBasis)
|
|
35152
35993
|
}),
|
|
35153
35994
|
buckets: exports_Schema.Array(SyncBucket),
|
|
35154
35995
|
coverage: exports_Schema.Array(SyncCoverage),
|
|
35155
35996
|
providerHints: exports_Schema.optionalKey(exports_Schema.Array(ProviderHint)),
|
|
35156
35997
|
snapshotAt: exports_Schema.optionalKey(UtcInstant)
|
|
35157
|
-
}).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, (
|
|
35158
|
-
bucket.hourStart,
|
|
35159
|
-
bucket.sessionKey,
|
|
35160
|
-
bucket.project,
|
|
35161
|
-
bucket.provider,
|
|
35162
|
-
bucket.billingProvider ?? null,
|
|
35163
|
-
bucket.model
|
|
35164
|
-
])) && distinct(payload.coverage, (entry) => entry.provider) && distinct(payload.providerHints ?? [], (hint) => JSON.stringify([hint.provider, hint.hourStart, hint.plan])), {
|
|
35998
|
+
}).check(exports_Schema.makeFilter((payload) => (payload.version >= 2 || payload.buckets.every((bucket) => bucket.billingProvider === undefined)) && (payload.version >= 3 || !payload.buckets.some(partlyPriced)) && distinct(payload.buckets, bucketKey) && distinct(payload.coverage, (entry) => entry.provider) && distinct(payload.providerHints ?? [], (hint) => JSON.stringify([hint.provider, hint.hourStart, hint.plan])), {
|
|
35165
35999
|
expected: "unique bucket keys, coverage providers, and plan hints, and a version carrying every bucket"
|
|
35166
36000
|
}), exports_Schema.makeFilter((payload) => {
|
|
35167
36001
|
const replaced = replacedProviders(payload.coverage);
|
|
35168
36002
|
return [...payload.buckets, ...payload.providerHints ?? []].every((entry) => replaced.has(entry.provider) && entry.hourStart >= payload.window.start && entry.hourStart < payload.window.end);
|
|
35169
36003
|
}));
|
|
36004
|
+
var maxRepriceBuckets = 20000;
|
|
36005
|
+
var RepricePayload = exports_Schema.Struct({
|
|
36006
|
+
version: exports_Schema.Literal(1),
|
|
36007
|
+
clientVersion: NonEmptyText,
|
|
36008
|
+
pricing: exports_Schema.Struct({
|
|
36009
|
+
status: PriceBook.fields.status,
|
|
36010
|
+
fetchedAt: exports_Schema.NullOr(UtcInstant),
|
|
36011
|
+
source: Text,
|
|
36012
|
+
basis: PricingBasis
|
|
36013
|
+
}),
|
|
36014
|
+
buckets: exports_Schema.Array(SyncBucket).check(exports_Schema.isMaxLength(maxRepriceBuckets))
|
|
36015
|
+
}).check(exports_Schema.makeFilter((payload) => distinct(payload.buckets, bucketKey), {
|
|
36016
|
+
expected: "unique bucket keys"
|
|
36017
|
+
}));
|
|
36018
|
+
var maxRepriceBytes = 12 * 1024 * 1024;
|
|
36019
|
+
function repriceChunks(buckets) {
|
|
36020
|
+
const chunks2 = [];
|
|
36021
|
+
let chunk = [];
|
|
36022
|
+
let bytes2 = 0;
|
|
36023
|
+
for (const bucket of buckets) {
|
|
36024
|
+
const size7 = Buffer.byteLength(JSON.stringify(bucket)) + 1;
|
|
36025
|
+
if (chunk.length > 0 && (chunk.length >= maxRepriceBuckets || bytes2 + size7 > maxRepriceBytes)) {
|
|
36026
|
+
chunks2.push(chunk);
|
|
36027
|
+
chunk = [];
|
|
36028
|
+
bytes2 = 0;
|
|
36029
|
+
}
|
|
36030
|
+
chunk.push(bucket);
|
|
36031
|
+
bytes2 += size7;
|
|
36032
|
+
}
|
|
36033
|
+
if (chunk.length > 0)
|
|
36034
|
+
chunks2.push(chunk);
|
|
36035
|
+
return chunks2;
|
|
36036
|
+
}
|
|
36037
|
+
function bucketKey(bucket) {
|
|
36038
|
+
return JSON.stringify([
|
|
36039
|
+
bucket.hourStart,
|
|
36040
|
+
bucket.sessionKey,
|
|
36041
|
+
bucket.project,
|
|
36042
|
+
bucket.provider,
|
|
36043
|
+
bucket.billingProvider ?? null,
|
|
36044
|
+
bucket.model
|
|
36045
|
+
]);
|
|
36046
|
+
}
|
|
35170
36047
|
function distinct(items, key) {
|
|
35171
36048
|
return new Set(items.map(key)).size === items.length;
|
|
35172
36049
|
}
|
|
@@ -35178,7 +36055,7 @@ function hourRange(range3) {
|
|
|
35178
36055
|
};
|
|
35179
36056
|
}
|
|
35180
36057
|
function sessionKey(provider, session) {
|
|
35181
|
-
return
|
|
36058
|
+
return createHash3("sha256").update(`${provider}\x00${session}`).digest("hex").slice(0, 32);
|
|
35182
36059
|
}
|
|
35183
36060
|
function sessionBuckets(pricing) {
|
|
35184
36061
|
const totals = new Map;
|
|
@@ -35196,7 +36073,7 @@ function sessionBuckets(pricing) {
|
|
|
35196
36073
|
model
|
|
35197
36074
|
]);
|
|
35198
36075
|
const previous = totals.get(key);
|
|
35199
|
-
const cost =
|
|
36076
|
+
const cost = priceRecord(record3, pricing).usd;
|
|
35200
36077
|
totals.set(key, {
|
|
35201
36078
|
record: previous?.record ?? record3,
|
|
35202
36079
|
project,
|
|
@@ -35284,7 +36161,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35284
36161
|
}
|
|
35285
36162
|
return request3;
|
|
35286
36163
|
});
|
|
35287
|
-
const scan2 = exports_Effect.fn("Ledger.scan")(function* (request3,
|
|
36164
|
+
const scan2 = exports_Effect.fn("Ledger.scan")(function* (request3, range3, locate, collect2, notice, onWarning) {
|
|
35288
36165
|
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);
|
|
35289
36166
|
const chatgptRequests = exports_Result.isSuccess(hints) ? hints.success : new Map;
|
|
35290
36167
|
if (exports_Result.isFailure(hints))
|
|
@@ -35295,6 +36172,8 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35295
36172
|
const settledFiles = new Set;
|
|
35296
36173
|
const coverage = [];
|
|
35297
36174
|
const inherited = [];
|
|
36175
|
+
const deferred = [];
|
|
36176
|
+
const opencode = opencodeHistory((value5) => path.normalize(value5));
|
|
35298
36177
|
for (const source of request3.sources) {
|
|
35299
36178
|
let files = 0;
|
|
35300
36179
|
let filesBeforeWindow = 0;
|
|
@@ -35331,13 +36210,23 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35331
36210
|
for (const record3 of result6.inherited) {
|
|
35332
36211
|
const slot = locate(record3.timestamp);
|
|
35333
36212
|
if (slot !== undefined && totalTokens(record3.tokens) > 0)
|
|
35334
|
-
inherited.push(place(record3, slot));
|
|
36213
|
+
inherited.push(exports_Effect.suspend(() => place(opencode.settle(record3), slot)));
|
|
36214
|
+
}
|
|
36215
|
+
for (const record3 of result6.deferred) {
|
|
36216
|
+
const slot = locate(record3.timestamp);
|
|
36217
|
+
if (slot !== undefined && totalTokens(record3.tokens) > 0)
|
|
36218
|
+
deferred.push(exports_Effect.suspend(() => {
|
|
36219
|
+
const classified = opencode.classify(record3);
|
|
36220
|
+
return classified.copy ? exports_Effect.sync(() => {
|
|
36221
|
+
inherited.push(exports_Effect.suspend(() => place(opencode.settle(classified.record), slot)));
|
|
36222
|
+
}) : place(classified.record, slot);
|
|
36223
|
+
}));
|
|
35335
36224
|
}
|
|
35336
36225
|
});
|
|
35337
36226
|
const scanFile = exports_Effect.fn("Ledger.scanFile")(function* (file2, info2) {
|
|
35338
36227
|
const canonical = yield* fs.realPath(file2);
|
|
35339
36228
|
const identity3 = `${source.provider}:${canonical}`;
|
|
35340
|
-
const settled = settledBefore(source, file2, info2, start - modifiedSlack);
|
|
36229
|
+
const settled = settledBefore(path, source, file2, info2, range3.start - modifiedSlack);
|
|
35341
36230
|
if (visitedFiles.has(identity3) || settled && settledFiles.has(identity3)) {
|
|
35342
36231
|
warnings.add("An overlapping source was counted once; the first source's project override wins.");
|
|
35343
36232
|
return;
|
|
@@ -35348,10 +36237,10 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35348
36237
|
return;
|
|
35349
36238
|
}
|
|
35350
36239
|
visitedFiles.add(identity3);
|
|
35351
|
-
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.exhaustive);
|
|
36240
|
+
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);
|
|
35352
36241
|
let lineNumber = 0;
|
|
35353
36242
|
files++;
|
|
35354
|
-
const lines = source.provider === "copilot" && canonical.endsWith(".db") ? exports_Stream.fromIterableEffect(copilotDatabaseLines(canonical)) : fs.stream(canonical).pipe(exports_Stream.decodeText, exports_Stream.splitLines);
|
|
36243
|
+
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);
|
|
35355
36244
|
yield* lines.pipe(exports_Stream.runForEach(exports_Effect.fn("Ledger.line")(function* (line) {
|
|
35356
36245
|
lineNumber++;
|
|
35357
36246
|
if (!line.trim())
|
|
@@ -35370,6 +36259,8 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35370
36259
|
const result6 = yield* exports_Effect.gen(function* () {
|
|
35371
36260
|
const stat3 = yield* fs.stat(entry);
|
|
35372
36261
|
if (stat3.type === "Directory") {
|
|
36262
|
+
if (!descends(path, source, entry))
|
|
36263
|
+
return;
|
|
35373
36264
|
const canonical = yield* fs.realPath(entry);
|
|
35374
36265
|
if (visitedDirectories.has(canonical))
|
|
35375
36266
|
return;
|
|
@@ -35377,7 +36268,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35377
36268
|
const children = yield* fs.readDirectory(entry);
|
|
35378
36269
|
for (const child of children.toSorted().toReversed())
|
|
35379
36270
|
pending.push(path.join(entry, child));
|
|
35380
|
-
} else if (stat3.type === "File" && acceptsFile(source, entry)) {
|
|
36271
|
+
} else if (stat3.type === "File" && acceptsFile(path, source, entry)) {
|
|
35381
36272
|
yield* scanFile(entry, stat3);
|
|
35382
36273
|
}
|
|
35383
36274
|
}).pipe(exports_Effect.result);
|
|
@@ -35393,7 +36284,10 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35393
36284
|
const hintsFailed = source.provider === "copilot" && exports_Result.isFailure(hints);
|
|
35394
36285
|
if (hintsFailed)
|
|
35395
36286
|
warnings.add("Billing hints could not be read; stored Copilot usage will be kept.");
|
|
35396
|
-
const
|
|
36287
|
+
const unrecognised = source.provider === "opencode" && !missingRoot && failedFiles === 0 && files === 0 && filesBeforeWindow === 0;
|
|
36288
|
+
if (unrecognised)
|
|
36289
|
+
warnings.add("No OpenCode database or legacy message or session was found here.");
|
|
36290
|
+
const status = hintsFailed ? "failed" : missingRoot || unrecognised ? "missing" : failedFiles > 0 && files === 0 ? "failed" : failedFiles > 0 || malformedLines > 0 || skippedRecords > 0 ? "partial" : "ok";
|
|
35397
36291
|
coverage.push(() => ({
|
|
35398
36292
|
provider: source.provider,
|
|
35399
36293
|
source: source.path,
|
|
@@ -35407,6 +36301,8 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35407
36301
|
warnings: [...warnings]
|
|
35408
36302
|
}));
|
|
35409
36303
|
}
|
|
36304
|
+
for (const legacy of deferred)
|
|
36305
|
+
yield* legacy;
|
|
35410
36306
|
for (const copy4 of inherited)
|
|
35411
36307
|
yield* copy4;
|
|
35412
36308
|
return coverage.map((summarize) => summarize());
|
|
@@ -35415,16 +36311,16 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35415
36311
|
const request3 = yield* decode5(input);
|
|
35416
36312
|
const window = dayWindow(request3.since, request3.until, request3.timeZone);
|
|
35417
36313
|
const rows = new Map;
|
|
35418
|
-
const coverage = yield* scan2(request3, window
|
|
36314
|
+
const coverage = yield* scan2(request3, window, window.dayOf, (record3, { project }, day) => {
|
|
35419
36315
|
const key = JSON.stringify([project, day, record3.provider, record3.model]);
|
|
35420
|
-
const
|
|
36316
|
+
const { usd, base } = priceRecord(record3, request3.pricing);
|
|
35421
36317
|
rows.set(key, {
|
|
35422
36318
|
project,
|
|
35423
36319
|
day,
|
|
35424
36320
|
provider: record3.provider,
|
|
35425
36321
|
model: record3.model,
|
|
35426
|
-
pricePerMillion:
|
|
35427
|
-
...addUsage(rows.get(key), record3.tokens,
|
|
36322
|
+
pricePerMillion: base,
|
|
36323
|
+
...addUsage(rows.get(key), record3.tokens, usd)
|
|
35428
36324
|
});
|
|
35429
36325
|
});
|
|
35430
36326
|
return UsageReport.make({
|
|
@@ -35434,11 +36330,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35434
36330
|
timeZone: request3.timeZone.id,
|
|
35435
36331
|
currency: "USD",
|
|
35436
36332
|
costBasis: "api-equivalent",
|
|
35437
|
-
pricing:
|
|
35438
|
-
status: request3.pricing.status,
|
|
35439
|
-
fetchedAt: request3.pricing.fetchedAt,
|
|
35440
|
-
source: request3.pricing.source
|
|
35441
|
-
},
|
|
36333
|
+
pricing: provenance(request3.pricing),
|
|
35442
36334
|
rows: [...rows.values()].toSorted((a, b) => a.project.localeCompare(b.project) || a.day.localeCompare(b.day) || a.provider.localeCompare(b.provider) || a.model.localeCompare(b.model)),
|
|
35443
36335
|
coverage
|
|
35444
36336
|
});
|
|
@@ -35454,9 +36346,9 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35454
36346
|
const hints = planHints();
|
|
35455
36347
|
let earliest = requested.start;
|
|
35456
36348
|
const snapshotAt = yield* exports_Clock.currentTimeMillis;
|
|
35457
|
-
const coverage = yield* scan2(request3, from, (timestamp2) => timestamp2 >= from && timestamp2 < requested.end ? timestamp2 : undefined, (record3, attribution, timestamp2) => {
|
|
36349
|
+
const coverage = yield* scan2(request3, { start: from, end: requested.end }, (timestamp2) => timestamp2 >= from && timestamp2 < requested.end ? timestamp2 : undefined, (record3, attribution, timestamp2) => {
|
|
35458
36350
|
earliest = Math.min(earliest, timestamp2);
|
|
35459
|
-
buckets.add(record3, attribution
|
|
36351
|
+
buckets.add(record3, uploadedProject(attribution));
|
|
35460
36352
|
}, (plan) => {
|
|
35461
36353
|
earliest = Math.min(earliest, plan.timestamp);
|
|
35462
36354
|
hints.add(plan);
|
|
@@ -35477,11 +36369,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35477
36369
|
},
|
|
35478
36370
|
currency: "USD",
|
|
35479
36371
|
costBasis: "api-equivalent",
|
|
35480
|
-
pricing:
|
|
35481
|
-
status: request3.pricing.status,
|
|
35482
|
-
fetchedAt: request3.pricing.fetchedAt,
|
|
35483
|
-
source: request3.pricing.source
|
|
35484
|
-
},
|
|
36372
|
+
pricing: provenance(request3.pricing),
|
|
35485
36373
|
buckets: uploadedBuckets,
|
|
35486
36374
|
coverage: summary,
|
|
35487
36375
|
providerHints: hints.finish().filter((hint) => replaced.has(hint.provider)),
|
|
@@ -35491,22 +36379,78 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
|
|
|
35491
36379
|
})));
|
|
35492
36380
|
return { payload, since };
|
|
35493
36381
|
});
|
|
36382
|
+
const repriceBuckets = exports_Effect.fn("Ledger.repriceBuckets")(function* (input, provider, range3) {
|
|
36383
|
+
const request3 = yield* decode5(input);
|
|
36384
|
+
const hours2 = hourRange(range3);
|
|
36385
|
+
if (hours2.start !== range3.start || hours2.end !== range3.end || range3.start >= range3.end)
|
|
36386
|
+
return yield* new InvalidRequest({ message: "Expected a range of whole UTC hours." });
|
|
36387
|
+
const buckets = sessionBuckets(request3.pricing);
|
|
36388
|
+
const coverage = yield* scan2({ ...request3, sources: request3.sources.filter((source) => source.provider === provider) }, range3, (timestamp2) => timestamp2 >= range3.start && timestamp2 < range3.end ? timestamp2 : undefined, (record3, attribution) => buckets.add(record3, uploadedProject(attribution)), () => {
|
|
36389
|
+
return;
|
|
36390
|
+
});
|
|
36391
|
+
const summary = providerCoverage(coverage).find((entry) => entry.provider === provider) ?? {
|
|
36392
|
+
provider,
|
|
36393
|
+
status: "missing",
|
|
36394
|
+
files: 0,
|
|
36395
|
+
filesBeforeWindow: 0,
|
|
36396
|
+
unreadable: 0,
|
|
36397
|
+
malformedLines: 0,
|
|
36398
|
+
skippedRecords: 0,
|
|
36399
|
+
duplicates: 0
|
|
36400
|
+
};
|
|
36401
|
+
return {
|
|
36402
|
+
buckets: replacedProviders([summary]).has(provider) ? buckets.finish() : [],
|
|
36403
|
+
coverage: summary
|
|
36404
|
+
};
|
|
36405
|
+
});
|
|
35494
36406
|
return Ledger.of({
|
|
35495
36407
|
report,
|
|
35496
36408
|
syncPayload: (request3, client, onWarning) => exports_Effect.map(payloadFrom(request3, client, false, onWarning), ({ payload }) => payload),
|
|
35497
|
-
historyPayload: (request3, client, onWarning) => payloadFrom(request3, client, true, onWarning)
|
|
36409
|
+
historyPayload: (request3, client, onWarning) => payloadFrom(request3, client, true, onWarning),
|
|
36410
|
+
repriceBuckets
|
|
35498
36411
|
});
|
|
35499
36412
|
}));
|
|
35500
36413
|
}
|
|
35501
|
-
function
|
|
36414
|
+
function uploadedProject(attribution) {
|
|
36415
|
+
return attribution.shareable ? attribution.project : unattributed;
|
|
36416
|
+
}
|
|
36417
|
+
function provenance(pricing) {
|
|
36418
|
+
const { status, fetchedAt, source } = pricing;
|
|
36419
|
+
return pricing.basis === undefined ? { status, fetchedAt, source } : { status, fetchedAt, source, basis: pricing.basis };
|
|
36420
|
+
}
|
|
36421
|
+
function acceptsFile(path, source, file2) {
|
|
35502
36422
|
if (source.path === file2)
|
|
35503
36423
|
return true;
|
|
35504
36424
|
if (source.provider === "grok")
|
|
35505
36425
|
return file2.endsWith("/updates.jsonl") || file2.endsWith("\\updates.jsonl");
|
|
36426
|
+
if (source.provider === "opencode")
|
|
36427
|
+
return opencodeFile(path, file2) !== "database" || opencodeDatabaseName.test(path.basename(file2));
|
|
35506
36428
|
return file2.endsWith(".jsonl") || source.provider === "copilot" && file2.endsWith(".db");
|
|
35507
36429
|
}
|
|
35508
|
-
function
|
|
35509
|
-
|
|
36430
|
+
function opencodeFile(path, file2) {
|
|
36431
|
+
const name = path.basename(file2);
|
|
36432
|
+
if (!name.endsWith(".json"))
|
|
36433
|
+
return "database";
|
|
36434
|
+
return name.startsWith("msg_") ? "message" : name.startsWith("ses_") ? "session" : "database";
|
|
36435
|
+
}
|
|
36436
|
+
var opencodeElsewhere = new Set([
|
|
36437
|
+
"bin",
|
|
36438
|
+
"log",
|
|
36439
|
+
"part",
|
|
36440
|
+
"repos",
|
|
36441
|
+
"session_diff",
|
|
36442
|
+
"session_share",
|
|
36443
|
+
"share",
|
|
36444
|
+
"shell",
|
|
36445
|
+
"snapshot",
|
|
36446
|
+
"todo",
|
|
36447
|
+
"tool-output"
|
|
36448
|
+
]);
|
|
36449
|
+
function descends(path, source, directory) {
|
|
36450
|
+
return source.provider !== "opencode" || directory === source.path || !opencodeElsewhere.has(path.basename(directory));
|
|
36451
|
+
}
|
|
36452
|
+
function settledBefore(path, source, file2, info2, cutoff) {
|
|
36453
|
+
if (source.path === file2 || source.provider === "copilot" || source.provider === "opencode" && opencodeFile(path, file2) !== "message")
|
|
35510
36454
|
return false;
|
|
35511
36455
|
return exports_Option.isSome(info2.mtime) && info2.mtime.value.getTime() < cutoff;
|
|
35512
36456
|
}
|
|
@@ -41627,10 +42571,10 @@ function lex(argv) {
|
|
|
41627
42571
|
}
|
|
41628
42572
|
var negativeNumberRegex = /^-(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
|
|
41629
42573
|
var lexTokens = (args2) => {
|
|
41630
|
-
const
|
|
42574
|
+
const tokens2 = [];
|
|
41631
42575
|
for (const arg of args2) {
|
|
41632
42576
|
if (!arg.startsWith("-") || negativeNumberRegex.test(arg)) {
|
|
41633
|
-
|
|
42577
|
+
tokens2.push({
|
|
41634
42578
|
_tag: "Value",
|
|
41635
42579
|
value: arg
|
|
41636
42580
|
});
|
|
@@ -41639,14 +42583,14 @@ var lexTokens = (args2) => {
|
|
|
41639
42583
|
if (equalIndex !== -1) {
|
|
41640
42584
|
const name = arg.slice(2, equalIndex);
|
|
41641
42585
|
const value5 = arg.slice(equalIndex + 1);
|
|
41642
|
-
|
|
42586
|
+
tokens2.push({
|
|
41643
42587
|
_tag: "LongOption",
|
|
41644
42588
|
name,
|
|
41645
42589
|
raw: arg,
|
|
41646
42590
|
value: value5
|
|
41647
42591
|
});
|
|
41648
42592
|
} else {
|
|
41649
|
-
|
|
42593
|
+
tokens2.push({
|
|
41650
42594
|
_tag: "LongOption",
|
|
41651
42595
|
name: arg.slice(2),
|
|
41652
42596
|
raw: arg
|
|
@@ -41658,7 +42602,7 @@ var lexTokens = (args2) => {
|
|
|
41658
42602
|
if (equalIndex !== -1) {
|
|
41659
42603
|
const flag = flags.slice(0, equalIndex);
|
|
41660
42604
|
const value5 = flags.slice(equalIndex + 1);
|
|
41661
|
-
|
|
42605
|
+
tokens2.push({
|
|
41662
42606
|
_tag: "ShortOption",
|
|
41663
42607
|
flag,
|
|
41664
42608
|
raw: `-${flag}`,
|
|
@@ -41666,7 +42610,7 @@ var lexTokens = (args2) => {
|
|
|
41666
42610
|
});
|
|
41667
42611
|
} else {
|
|
41668
42612
|
for (const ch of flags) {
|
|
41669
|
-
|
|
42613
|
+
tokens2.push({
|
|
41670
42614
|
_tag: "ShortOption",
|
|
41671
42615
|
flag: ch,
|
|
41672
42616
|
raw: `-${ch}`
|
|
@@ -41674,13 +42618,13 @@ var lexTokens = (args2) => {
|
|
|
41674
42618
|
}
|
|
41675
42619
|
}
|
|
41676
42620
|
} else {
|
|
41677
|
-
|
|
42621
|
+
tokens2.push({
|
|
41678
42622
|
_tag: "Value",
|
|
41679
42623
|
value: arg
|
|
41680
42624
|
});
|
|
41681
42625
|
}
|
|
41682
42626
|
}
|
|
41683
|
-
return
|
|
42627
|
+
return tokens2;
|
|
41684
42628
|
};
|
|
41685
42629
|
|
|
41686
42630
|
// node_modules/.bun/effect@4.0.0/node_modules/effect/dist/cli/internal/auto-suggest.js
|
|
@@ -41717,7 +42661,7 @@ var getCommandPath = (parsedInput) => match(parsedInput.subcommand, {
|
|
|
41717
42661
|
});
|
|
41718
42662
|
var parseArgs = (lexResult, command, commandPath = []) => gen4(function* () {
|
|
41719
42663
|
const {
|
|
41720
|
-
tokens,
|
|
42664
|
+
tokens: tokens2,
|
|
41721
42665
|
trailingOperands: afterEndOfOptions
|
|
41722
42666
|
} = lexResult;
|
|
41723
42667
|
const newCommandPath = [...commandPath, command.name];
|
|
@@ -41736,7 +42680,7 @@ var parseArgs = (lexResult, command, commandPath = []) => gen4(function* () {
|
|
|
41736
42680
|
inheritedFlagRegistry,
|
|
41737
42681
|
localFlagNames: flagParams.filter((param) => !inheritedNames.has(param.name)).map((param) => param.name)
|
|
41738
42682
|
};
|
|
41739
|
-
const result6 = scanCommandLevel(
|
|
42683
|
+
const result6 = scanCommandLevel(tokens2, context3);
|
|
41740
42684
|
if (result6._tag === "Leaf") {
|
|
41741
42685
|
return {
|
|
41742
42686
|
flags: result6.flags,
|
|
@@ -41765,12 +42709,12 @@ var parseArgs = (lexResult, command, commandPath = []) => gen4(function* () {
|
|
|
41765
42709
|
}
|
|
41766
42710
|
};
|
|
41767
42711
|
});
|
|
41768
|
-
var makeCursor = (
|
|
42712
|
+
var makeCursor = (tokens2) => {
|
|
41769
42713
|
let i = 0;
|
|
41770
42714
|
return {
|
|
41771
|
-
peek: () =>
|
|
41772
|
-
take: () =>
|
|
41773
|
-
rest: () =>
|
|
42715
|
+
peek: () => tokens2[i],
|
|
42716
|
+
take: () => tokens2[i++],
|
|
42717
|
+
rest: () => tokens2.slice(i)
|
|
41774
42718
|
};
|
|
41775
42719
|
};
|
|
41776
42720
|
var createFlagRegistry = (params) => {
|
|
@@ -41947,11 +42891,11 @@ var consumeFlagValueWithTokens = (cursor, token, spec, negated = false) => {
|
|
|
41947
42891
|
tokens: []
|
|
41948
42892
|
};
|
|
41949
42893
|
};
|
|
41950
|
-
var consumeKnownFlags = (
|
|
42894
|
+
var consumeKnownFlags = (tokens2, registry) => {
|
|
41951
42895
|
const flagMap = createEmptyFlagMap(registry.params);
|
|
41952
42896
|
const remainder2 = [];
|
|
41953
42897
|
const errors = [];
|
|
41954
|
-
const cursor = makeCursor(
|
|
42898
|
+
const cursor = makeCursor(tokens2);
|
|
41955
42899
|
for (let t = cursor.take();t; t = cursor.take()) {
|
|
41956
42900
|
if (!isFlagToken(t)) {
|
|
41957
42901
|
remainder2.push(t);
|
|
@@ -42018,14 +42962,14 @@ var localFlagWouldPrecedeSubcommand = (token, remainingTokens, resolved, subInde
|
|
|
42018
42962
|
}
|
|
42019
42963
|
return false;
|
|
42020
42964
|
};
|
|
42021
|
-
var consumeGlobalFlags = (
|
|
42965
|
+
var consumeGlobalFlags = (tokens2, command, registry) => {
|
|
42022
42966
|
const flagMap = createEmptyFlagMap(registry.params);
|
|
42023
42967
|
const errors = [];
|
|
42024
|
-
const consumeLevel = (
|
|
42968
|
+
const consumeLevel = (tokens3, command2, ignoredRegistries) => {
|
|
42025
42969
|
const localRegistry = createFlagRegistry(extractFlagParams(command2));
|
|
42026
42970
|
const inheritedRegistry = createFlagRegistry(extractContextFlagParams(command2));
|
|
42027
42971
|
const subIndex = buildSubcommandIndex(command2.subcommands);
|
|
42028
|
-
const cursor = makeCursor(
|
|
42972
|
+
const cursor = makeCursor(tokens3);
|
|
42029
42973
|
const remainder2 = [];
|
|
42030
42974
|
let awaitingFirstValue = true;
|
|
42031
42975
|
for (let token = cursor.take();token; token = cursor.take()) {
|
|
@@ -42077,7 +43021,7 @@ var consumeGlobalFlags = (tokens, command, registry) => {
|
|
|
42077
43021
|
};
|
|
42078
43022
|
return {
|
|
42079
43023
|
flagMap,
|
|
42080
|
-
remainder: consumeLevel(
|
|
43024
|
+
remainder: consumeLevel(tokens2, command, []),
|
|
42081
43025
|
errors
|
|
42082
43026
|
};
|
|
42083
43027
|
};
|
|
@@ -42200,8 +43144,8 @@ var processValue = (value5, cursor, context3, state) => {
|
|
|
42200
43144
|
state.arguments.push(value5);
|
|
42201
43145
|
return;
|
|
42202
43146
|
};
|
|
42203
|
-
var scanCommandLevel = (
|
|
42204
|
-
const cursor = makeCursor(
|
|
43147
|
+
var scanCommandLevel = (tokens2, context3) => {
|
|
43148
|
+
const cursor = makeCursor(tokens2);
|
|
42205
43149
|
const state = createParseState(context3.flagRegistry);
|
|
42206
43150
|
for (let token = cursor.take();token; token = cursor.take()) {
|
|
42207
43151
|
if (isFlagToken(token)) {
|
|
@@ -42704,7 +43648,7 @@ var runWith2 = (command, config) => {
|
|
|
42704
43648
|
builtIns
|
|
42705
43649
|
} = yield* CliConfig;
|
|
42706
43650
|
const {
|
|
42707
|
-
tokens,
|
|
43651
|
+
tokens: tokens2,
|
|
42708
43652
|
trailingOperands
|
|
42709
43653
|
} = lex(args2);
|
|
42710
43654
|
const allFlags = getGlobalFlagsForCommandTree(command, builtIns);
|
|
@@ -42714,7 +43658,7 @@ var runWith2 = (command, config) => {
|
|
|
42714
43658
|
flagMap,
|
|
42715
43659
|
remainder: remainder2,
|
|
42716
43660
|
errors: globalFlagErrors
|
|
42717
|
-
} = consumeGlobalFlags(
|
|
43661
|
+
} = consumeGlobalFlags(tokens2, command, globalRegistry);
|
|
42718
43662
|
const emptyArgs = {
|
|
42719
43663
|
flags: flagMap,
|
|
42720
43664
|
arguments: []
|
|
@@ -42809,7 +43753,7 @@ var runWith2 = (command, config) => {
|
|
|
42809
43753
|
// packages/cli/package.json
|
|
42810
43754
|
var package_default = {
|
|
42811
43755
|
name: "@ponbac/token-ledger",
|
|
42812
|
-
version: "0.
|
|
43756
|
+
version: "0.10.0",
|
|
42813
43757
|
private: true,
|
|
42814
43758
|
type: "module",
|
|
42815
43759
|
bin: {
|
|
@@ -43974,6 +44918,51 @@ var saveSyncSettings = exports_Effect.fn("Settings.saveSync")(function* (directo
|
|
|
43974
44918
|
}).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: `Cannot save ${file2}.` })));
|
|
43975
44919
|
return file2;
|
|
43976
44920
|
});
|
|
44921
|
+
var CompletedReprice = exports_Schema.Struct({
|
|
44922
|
+
server: exports_Schema.String,
|
|
44923
|
+
provider: Provider,
|
|
44924
|
+
basis: PricingBasis,
|
|
44925
|
+
from: exports_Schema.DateTimeUtcFromString,
|
|
44926
|
+
coveredUntil: exports_Schema.DateTimeUtcFromString
|
|
44927
|
+
});
|
|
44928
|
+
var Repricing = exports_Schema.Struct({
|
|
44929
|
+
version: exports_Schema.Literal(1),
|
|
44930
|
+
completed: exports_Schema.Array(CompletedReprice)
|
|
44931
|
+
});
|
|
44932
|
+
var loadRepricing = exports_Effect.fn("Settings.loadRepricing")(function* (directory) {
|
|
44933
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
44934
|
+
const path = yield* exports_Path.Path;
|
|
44935
|
+
return yield* fs.readFileString(path.join(directory, "repricing.json")).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(Repricing))), exports_Effect.map((repricing) => repricing.completed), exports_Effect.orElseSucceed(() => []));
|
|
44936
|
+
});
|
|
44937
|
+
var saveRepricing = exports_Effect.fn("Settings.saveRepricing")(function* (directory, completed) {
|
|
44938
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
44939
|
+
const path = yield* exports_Path.Path;
|
|
44940
|
+
const file2 = path.join(directory, "repricing.json");
|
|
44941
|
+
yield* exports_Effect.gen(function* () {
|
|
44942
|
+
const repricing = yield* exports_Schema.encodeEffect(Repricing)({ version: 1, completed });
|
|
44943
|
+
yield* fs.makeDirectory(directory, { recursive: true });
|
|
44944
|
+
const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
|
|
44945
|
+
directory,
|
|
44946
|
+
prefix: ".repricing-"
|
|
44947
|
+
});
|
|
44948
|
+
const temporary = path.join(temporaryDirectory, "repricing.json");
|
|
44949
|
+
yield* fs.writeFileString(temporary, `${JSON.stringify(repricing, null, 2)}
|
|
44950
|
+
`, { flag: "wx" });
|
|
44951
|
+
yield* fs.rename(temporary, file2);
|
|
44952
|
+
}).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: "Cannot save repricing.json in the settings directory." })));
|
|
44953
|
+
});
|
|
44954
|
+
var ScheduleSettings = exports_Schema.Struct({ version: exports_Schema.Literal(1) });
|
|
44955
|
+
var scheduleSettled = exports_Effect.fn("Settings.scheduleSettled")(function* (directory) {
|
|
44956
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
44957
|
+
const path = yield* exports_Path.Path;
|
|
44958
|
+
return yield* fs.readFileString(path.join(directory, "schedule.json")).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(ScheduleSettings))), exports_Effect.as(true), exports_Effect.orElseSucceed(() => false));
|
|
44959
|
+
});
|
|
44960
|
+
var settleSchedule = exports_Effect.fn("Settings.settleSchedule")(function* (directory) {
|
|
44961
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
44962
|
+
const path = yield* exports_Path.Path;
|
|
44963
|
+
yield* fs.makeDirectory(directory, { recursive: true }).pipe(exports_Effect.andThen(fs.writeFileString(path.join(directory, "schedule.json"), `${JSON.stringify({ version: 1 }, null, 2)}
|
|
44964
|
+
`)), exports_Effect.mapError(() => new SettingsError({ message: "Cannot save schedule.json in the settings directory." })));
|
|
44965
|
+
});
|
|
43977
44966
|
|
|
43978
44967
|
// packages/cli/src/schedule.ts
|
|
43979
44968
|
class ScheduleError extends exports_Schema.TaggedError()("ScheduleError", {
|
|
@@ -43991,6 +44980,8 @@ var intervals = [
|
|
|
43991
44980
|
["12h", 12],
|
|
43992
44981
|
["24h", 24]
|
|
43993
44982
|
];
|
|
44983
|
+
var defaultInterval = 2;
|
|
44984
|
+
var isTimeOfDay = exports_Schema.is(TimeOfDay);
|
|
43994
44985
|
function syncTimes(job) {
|
|
43995
44986
|
const hour2 = Number(job.at.slice(0, 2));
|
|
43996
44987
|
const minute = job.at.slice(3);
|
|
@@ -44002,6 +44993,11 @@ var unit = "token-ledger-sync";
|
|
|
44002
44993
|
var label = "com.github.ponbac.token-ledger.sync";
|
|
44003
44994
|
var task = "token-ledger sync";
|
|
44004
44995
|
var packageSpec = "@ponbac/token-ledger@latest";
|
|
44996
|
+
var readJob = (file2) => exports_Effect.gen(function* () {
|
|
44997
|
+
const fs = yield* exports_FileSystem.FileSystem;
|
|
44998
|
+
return (yield* fs.exists(file2)) ? exports_Option.some(yield* fs.readFileString(file2)) : exports_Option.none();
|
|
44999
|
+
}).pipe(exports_Effect.mapError(() => new ScheduleError({ message: `Cannot read ${file2}.` })));
|
|
45000
|
+
var dailyAt = (hour2, minute) => exports_Option.filter(exports_Option.some(`${hour2.padStart(2, "0")}:${minute.padStart(2, "0")}`), isTimeOfDay);
|
|
44005
45001
|
function run6(outcome, program, args2, hint = "") {
|
|
44006
45002
|
return Action3.Run({
|
|
44007
45003
|
program,
|
|
@@ -44033,6 +45029,17 @@ var posixScript = (job) => [
|
|
|
44033
45029
|
].join("; ");
|
|
44034
45030
|
var posixJob = (job) => quotable(job, /\p{Cc}/u, "a control character");
|
|
44035
45031
|
var systemdQuoted = (value5) => `"${value5.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("%", "%%").replaceAll("$", () => "$$")}"`;
|
|
45032
|
+
var timerUnit = (job) => `[Unit]
|
|
45033
|
+
Description=AI usage sync ${job.every === 24 ? "once a day" : `every ${job.every}h`}
|
|
45034
|
+
|
|
45035
|
+
[Timer]
|
|
45036
|
+
OnCalendar=*-*-* ${syncTimes(job).map((time2) => time2.slice(0, 2)).join(",")}:${job.at.slice(3)}:00
|
|
45037
|
+
Persistent=true
|
|
45038
|
+
RandomizedDelaySec=10m
|
|
45039
|
+
|
|
45040
|
+
[Install]
|
|
45041
|
+
WantedBy=timers.target
|
|
45042
|
+
`;
|
|
44036
45043
|
function systemdTimer(directory) {
|
|
44037
45044
|
const service4 = `${directory}/${unit}.service`;
|
|
44038
45045
|
const timer = `${directory}/${unit}.timer`;
|
|
@@ -44051,20 +45058,7 @@ Type=oneshot
|
|
|
44051
45058
|
ExecStart=/bin/sh -lc ${systemdQuoted(posixScript(job2))}
|
|
44052
45059
|
`
|
|
44053
45060
|
}),
|
|
44054
|
-
Action3.Write({
|
|
44055
|
-
file: timer,
|
|
44056
|
-
contents: `[Unit]
|
|
44057
|
-
Description=AI usage sync ${job2.every === 24 ? "once a day" : `every ${job2.every}h`}
|
|
44058
|
-
|
|
44059
|
-
[Timer]
|
|
44060
|
-
OnCalendar=*-*-* ${syncTimes(job2).map((time2) => time2.slice(0, 2)).join(",")}:${job2.at.slice(3)}:00
|
|
44061
|
-
Persistent=true
|
|
44062
|
-
RandomizedDelaySec=10m
|
|
44063
|
-
|
|
44064
|
-
[Install]
|
|
44065
|
-
WantedBy=timers.target
|
|
44066
|
-
`
|
|
44067
|
-
}),
|
|
45061
|
+
Action3.Write({ file: timer, contents: timerUnit(job2) }),
|
|
44068
45062
|
systemctl("required", ["daemon-reload"]),
|
|
44069
45063
|
systemctl("required", ["enable", `${unit}.timer`]),
|
|
44070
45064
|
systemctl("required", ["restart", `${unit}.timer`])
|
|
@@ -44080,31 +45074,45 @@ WantedBy=timers.target
|
|
|
44080
45074
|
gone: [3, 4]
|
|
44081
45075
|
})
|
|
44082
45076
|
],
|
|
44083
|
-
status: [systemctl("reported", ["status", "--no-pager", `${unit}.timer`, `${unit}.service`])]
|
|
45077
|
+
status: [systemctl("reported", ["status", "--no-pager", `${unit}.timer`, `${unit}.service`])],
|
|
45078
|
+
dailyJob: readJob(timer).pipe(exports_Effect.map(exports_Option.flatMap((contents) => exports_Option.map(exports_Option.flatMap(exports_Option.fromNullishOr(/^OnCalendar=\*-\*-\* (\d{2}):(\d{2}):00$/m.exec(contents)), ([, hour2 = "", minute = ""]) => dailyAt(hour2, minute)), (at) => ({
|
|
45079
|
+
at,
|
|
45080
|
+
retime: (every4) => [
|
|
45081
|
+
Action3.Write({ file: timer, contents: timerUnit({ at, every: every4 }) }),
|
|
45082
|
+
systemctl("required", ["daemon-reload"]),
|
|
45083
|
+
systemctl("required", ["try-restart", `${unit}.timer`])
|
|
45084
|
+
],
|
|
45085
|
+
undo: [Action3.Write({ file: timer, contents })]
|
|
45086
|
+
})))))
|
|
44084
45087
|
};
|
|
44085
45088
|
}
|
|
44086
45089
|
var xmlText = (value5) => value5.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
45090
|
+
var calendarInterval = (job) => `<key>StartCalendarInterval</key>
|
|
45091
|
+
<array>
|
|
45092
|
+
${syncTimes(job).map((time2) => {
|
|
45093
|
+
const [hour2, minute] = time2.split(":").map(Number);
|
|
45094
|
+
return ` <dict>
|
|
45095
|
+
<key>Hour</key>
|
|
45096
|
+
<integer>${hour2}</integer>
|
|
45097
|
+
<key>Minute</key>
|
|
45098
|
+
<integer>${minute}</integer>
|
|
45099
|
+
</dict>`;
|
|
45100
|
+
}).join(`
|
|
45101
|
+
`)}
|
|
45102
|
+
</array>`;
|
|
45103
|
+
var startCalendarInterval = /<key>StartCalendarInterval<\/key>\s*(?:<dict>[\s\S]*?<\/dict>|<array>[\s\S]*?<\/array>)/;
|
|
45104
|
+
var hourAndMinute = /<key>Hour<\/key>\s*<integer>(\d{1,2})<\/integer>\s*<key>Minute<\/key>\s*<integer>(\d{1,2})<\/integer>/g;
|
|
45105
|
+
var reloadAgent = 'while kill -0 "$PPID" 2>/dev/null; do sleep 1; done; launchctl bootout "$1"; for attempt in 1 2 3 4 5; do launchctl bootstrap "$2" "$3" && break; sleep 1; done';
|
|
44087
45106
|
function launchAgent(home, uid) {
|
|
44088
45107
|
const plist = `${home}/Library/LaunchAgents/${label}.plist`;
|
|
44089
45108
|
const log3 = `${home}/Library/Logs/${unit}.log`;
|
|
44090
45109
|
const domain = `gui/${uid}`;
|
|
44091
45110
|
return {
|
|
44092
45111
|
name: "launchd agent",
|
|
44093
|
-
install: (job) => posixJob(job).pipe(exports_Effect.map((job2) =>
|
|
44094
|
-
|
|
44095
|
-
|
|
44096
|
-
|
|
44097
|
-
<key>Hour</key>
|
|
44098
|
-
<integer>${hour2}</integer>
|
|
44099
|
-
<key>Minute</key>
|
|
44100
|
-
<integer>${minute}</integer>
|
|
44101
|
-
</dict>`;
|
|
44102
|
-
}).join(`
|
|
44103
|
-
`);
|
|
44104
|
-
return [
|
|
44105
|
-
Action3.Write({
|
|
44106
|
-
file: plist,
|
|
44107
|
-
contents: `<?xml version="1.0" encoding="UTF-8"?>
|
|
45112
|
+
install: (job) => posixJob(job).pipe(exports_Effect.map((job2) => [
|
|
45113
|
+
Action3.Write({
|
|
45114
|
+
file: plist,
|
|
45115
|
+
contents: `<?xml version="1.0" encoding="UTF-8"?>
|
|
44108
45116
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
44109
45117
|
<plist version="1.0">
|
|
44110
45118
|
<dict>
|
|
@@ -44118,10 +45126,7 @@ function launchAgent(home, uid) {
|
|
|
44118
45126
|
</array>
|
|
44119
45127
|
<key>RunAtLoad</key>
|
|
44120
45128
|
<true/>
|
|
44121
|
-
|
|
44122
|
-
<array>
|
|
44123
|
-
${times}
|
|
44124
|
-
</array>
|
|
45129
|
+
${calendarInterval(job2)}
|
|
44125
45130
|
<key>StandardOutPath</key>
|
|
44126
45131
|
<string>${xmlText(log3)}</string>
|
|
44127
45132
|
<key>StandardErrorPath</key>
|
|
@@ -44129,17 +45134,35 @@ ${times}
|
|
|
44129
45134
|
</dict>
|
|
44130
45135
|
</plist>
|
|
44131
45136
|
`
|
|
44132
|
-
|
|
44133
|
-
|
|
44134
|
-
|
|
44135
|
-
|
|
44136
|
-
})),
|
|
45137
|
+
}),
|
|
45138
|
+
run6("silent", "launchctl", ["bootout", `${domain}/${label}`]),
|
|
45139
|
+
run6("required", "launchctl", ["bootstrap", domain, plist])
|
|
45140
|
+
])),
|
|
44137
45141
|
uninstall: [
|
|
44138
45142
|
run6("reported", "launchctl", ["bootout", `${domain}/${label}`]),
|
|
44139
45143
|
Action3.Remove({ file: plist }),
|
|
44140
45144
|
run6("absent", "launchctl", ["print", `${domain}/${label}`], "The agent is still loaded; launchd's reason is shown above.")
|
|
44141
45145
|
],
|
|
44142
|
-
status: [run6("reported", "launchctl", ["print", `${domain}/${label}`])]
|
|
45146
|
+
status: [run6("reported", "launchctl", ["print", `${domain}/${label}`])],
|
|
45147
|
+
dailyJob: readJob(plist).pipe(exports_Effect.map(exports_Option.flatMap((contents) => exports_Option.flatMap(exports_Option.fromNullishOr(startCalendarInterval.exec(contents)), ([block]) => {
|
|
45148
|
+
const times = [...block.matchAll(hourAndMinute)];
|
|
45149
|
+
const [, hour2 = "", minute = ""] = times[0] ?? [];
|
|
45150
|
+
return times.length === 1 ? exports_Option.map(dailyAt(hour2, minute), (at) => ({
|
|
45151
|
+
at,
|
|
45152
|
+
retime: (every4) => [
|
|
45153
|
+
Action3.Write({
|
|
45154
|
+
file: plist,
|
|
45155
|
+
contents: contents.replace(startCalendarInterval, () => calendarInterval({ at, every: every4 }))
|
|
45156
|
+
}),
|
|
45157
|
+
Action3.Launch({
|
|
45158
|
+
program: "/bin/sh",
|
|
45159
|
+
args: ["-c", reloadAgent, "sh", `${domain}/${label}`, domain, plist],
|
|
45160
|
+
shown: `/bin/sh -c '${reloadAgent}' sh ${domain}/${label} ${domain} ${plist}`
|
|
45161
|
+
})
|
|
45162
|
+
],
|
|
45163
|
+
undo: [Action3.Write({ file: plist, contents })]
|
|
45164
|
+
})) : exports_Option.none();
|
|
45165
|
+
}))))
|
|
44143
45166
|
};
|
|
44144
45167
|
}
|
|
44145
45168
|
var cmdWord = (value5) => /^[\w@+=:,./\\-]+$/.test(value5) ? value5 : `"${value5}"`;
|
|
@@ -44150,6 +45173,33 @@ var powershellArguments = (script) => [
|
|
|
44150
45173
|
Buffer.from(script, "utf16le").toString("base64")
|
|
44151
45174
|
];
|
|
44152
45175
|
var jscriptString = (value5) => JSON.stringify(value5).replaceAll(/[\u007f-\uffff]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
45176
|
+
var taskTrigger = (job) => [
|
|
45177
|
+
`$trigger = New-ScheduledTaskTrigger -Daily -At '${syncTimes(job)[0]}'`,
|
|
45178
|
+
...job.every === 24 ? [] : [
|
|
45179
|
+
`$trigger.Repetition = (New-ScheduledTaskTrigger -Once -At '${syncTimes(job)[0]}' -RepetitionInterval (New-TimeSpan -Hours ${job.every}) -RepetitionDuration (New-TimeSpan -Hours ${24 - job.every})).Repetition`
|
|
45180
|
+
]
|
|
45181
|
+
];
|
|
45182
|
+
var dailyTaskScript = [
|
|
45183
|
+
"$ErrorActionPreference = 'Stop'",
|
|
45184
|
+
`try { $task = Get-ScheduledTask -TaskName ${powershellString(task)} }`,
|
|
45185
|
+
"catch { if ($_.CategoryInfo.Category -eq 'ObjectNotFound') { exit 0 }; throw }",
|
|
45186
|
+
"if (@($task.Triggers).Count -eq 1) {",
|
|
45187
|
+
" $trigger = @($task.Triggers)[0]",
|
|
45188
|
+
" if ($trigger.CimClass.CimClassName -eq 'MSFT_TaskDailyTrigger' -and $trigger.DaysInterval -eq 1 -and -not $trigger.Repetition.Interval) {",
|
|
45189
|
+
" $trigger.StartBoundary.Substring(11, 5)",
|
|
45190
|
+
" }",
|
|
45191
|
+
"}"
|
|
45192
|
+
].join(`
|
|
45193
|
+
`);
|
|
45194
|
+
var powershell = (script) => Action3.Run({
|
|
45195
|
+
program: "powershell.exe",
|
|
45196
|
+
args: powershellArguments(script),
|
|
45197
|
+
shown: `powershell.exe ${powershellOptions.join(" ")} <the script below, as UTF-16LE Base64>
|
|
45198
|
+
${script}`,
|
|
45199
|
+
outcome: "required",
|
|
45200
|
+
hint: "",
|
|
45201
|
+
gone: []
|
|
45202
|
+
});
|
|
44153
45203
|
function taskScheduler(file2) {
|
|
44154
45204
|
return {
|
|
44155
45205
|
name: "Task Scheduler task",
|
|
@@ -44163,10 +45213,7 @@ function taskScheduler(file2) {
|
|
|
44163
45213
|
"$ErrorActionPreference = 'Stop'",
|
|
44164
45214
|
"$ProgressPreference = 'SilentlyContinue'",
|
|
44165
45215
|
`$action = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ${powershellString(`//B //Nologo //E:JScript "${file2}"`)}`,
|
|
44166
|
-
|
|
44167
|
-
...job2.every === 24 ? [] : [
|
|
44168
|
-
`$trigger.Repetition = (New-ScheduledTaskTrigger -Once -At '${syncTimes(job2)[0]}' -RepetitionInterval (New-TimeSpan -Hours ${job2.every}) -RepetitionDuration (New-TimeSpan -Hours ${24 - job2.every})).Repetition`
|
|
44169
|
-
],
|
|
45216
|
+
...taskTrigger(job2),
|
|
44170
45217
|
"$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
|
|
44171
45218
|
`Register-ScheduledTask -TaskName ${powershellString(task)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`
|
|
44172
45219
|
].join(`
|
|
@@ -44178,15 +45225,7 @@ function taskScheduler(file2) {
|
|
|
44178
45225
|
WScript.Quit(shell.Run(${jscriptString(`cmd.exe /d /v:off /s /c "${command}"`)}, 0, true));
|
|
44179
45226
|
`
|
|
44180
45227
|
}),
|
|
44181
|
-
|
|
44182
|
-
program: "powershell.exe",
|
|
44183
|
-
args: powershellArguments(script),
|
|
44184
|
-
shown: `powershell.exe ${powershellOptions.join(" ")} <the script below, as UTF-16LE Base64>
|
|
44185
|
-
${script}`,
|
|
44186
|
-
outcome: "required",
|
|
44187
|
-
hint: "",
|
|
44188
|
-
gone: []
|
|
44189
|
-
})
|
|
45228
|
+
powershell(script)
|
|
44190
45229
|
];
|
|
44191
45230
|
})),
|
|
44192
45231
|
uninstall: [
|
|
@@ -44194,7 +45233,33 @@ ${script}`,
|
|
|
44194
45233
|
run6("absent", "schtasks.exe", ["/Query", "/TN", task], "The task is still registered; Task Scheduler's reason is shown above."),
|
|
44195
45234
|
Action3.Remove({ file: file2 })
|
|
44196
45235
|
],
|
|
44197
|
-
status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])]
|
|
45236
|
+
status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])],
|
|
45237
|
+
dailyJob: exports_Effect.gen(function* () {
|
|
45238
|
+
const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
|
|
45239
|
+
const [output, code] = yield* spawner.spawn(exports_ChildProcess.make("powershell.exe", powershellArguments(dailyTaskScript), {
|
|
45240
|
+
stdin: "ignore",
|
|
45241
|
+
stderr: "inherit"
|
|
45242
|
+
})).pipe(exports_Effect.flatMap((handle) => exports_Effect.all([handle.stdout.pipe(exports_Stream.decodeText(), exports_Stream.mkString), handle.exitCode], {
|
|
45243
|
+
concurrency: "unbounded"
|
|
45244
|
+
})), exports_Effect.scoped, exports_Effect.mapError(() => new ScheduleError({ message: "Cannot ask Task Scheduler about the task." })));
|
|
45245
|
+
if (code !== 0)
|
|
45246
|
+
return yield* new ScheduleError({
|
|
45247
|
+
message: `Task Scheduler could not report the task; PowerShell exited with code ${code}.`
|
|
45248
|
+
});
|
|
45249
|
+
return exports_Option.map(exports_Option.filter(exports_Option.fromUndefinedOr(output.split(`
|
|
45250
|
+
`)[0]?.trim()), isTimeOfDay), (at) => ({
|
|
45251
|
+
at,
|
|
45252
|
+
retime: (every4) => [
|
|
45253
|
+
powershell([
|
|
45254
|
+
"$ErrorActionPreference = 'Stop'",
|
|
45255
|
+
...taskTrigger({ at, every: every4 }),
|
|
45256
|
+
`Set-ScheduledTask -TaskName ${powershellString(task)} -Trigger $trigger | Out-Null`
|
|
45257
|
+
].join(`
|
|
45258
|
+
`))
|
|
45259
|
+
],
|
|
45260
|
+
undo: []
|
|
45261
|
+
}));
|
|
45262
|
+
})
|
|
44198
45263
|
};
|
|
44199
45264
|
}
|
|
44200
45265
|
var hostScheduler = exports_Effect.gen(function* () {
|
|
@@ -44211,6 +45276,8 @@ ${contents.replaceAll(/^(?=.)/gm, " ")}`,
|
|
|
44211
45276
|
Remove: ({ file: file2 }) => `remove ${file2}
|
|
44212
45277
|
`,
|
|
44213
45278
|
Run: ({ shown }) => `run ${shown}
|
|
45279
|
+
`,
|
|
45280
|
+
Launch: ({ shown }) => `start ${shown}
|
|
44214
45281
|
`
|
|
44215
45282
|
})).join(`
|
|
44216
45283
|
`);
|
|
@@ -44228,9 +45295,29 @@ var perform = exports_Effect.fn("Schedule.perform")(function* (actions) {
|
|
|
44228
45295
|
return exports_Match.value(outcome).pipe(exports_Match.when("required", () => exports_Effect.filterOrFail(exit3, (code) => code === 0, (code) => new ScheduleError({
|
|
44229
45296
|
message: `${[program, ...args2.slice(0, 2)].join(" ")} failed with exit code ${code}. ${hint}`.trim()
|
|
44230
45297
|
}))), exports_Match.when("reported", () => exit3), exports_Match.when("silent", () => exports_Effect.ignore(exit3)), exports_Match.when("absent", () => exit3.pipe(exports_Effect.map((code) => gone.length === 0 ? code !== 0 : gone.includes(code)), exports_Effect.orElseSucceed(() => true), exports_Effect.filterOrFail((confirmed) => confirmed, () => new ScheduleError({ message: hint })))), exports_Match.exhaustive);
|
|
44231
|
-
}
|
|
45298
|
+
},
|
|
45299
|
+
Launch: ({ program, args: args2 }) => spawner.spawn(exports_ChildProcess.make(program, args2, {
|
|
45300
|
+
detached: true,
|
|
45301
|
+
stdin: "ignore",
|
|
45302
|
+
stdout: "ignore",
|
|
45303
|
+
stderr: "ignore"
|
|
45304
|
+
})).pipe(exports_Effect.flatMap((handle) => handle.unref), exports_Effect.scoped, exports_Effect.asVoid, exports_Effect.mapError(() => new ScheduleError({ message: `Cannot run ${program}.` })))
|
|
44232
45305
|
});
|
|
44233
45306
|
});
|
|
45307
|
+
var retimeDailySchedule = exports_Effect.fn("Schedule.retimeDailySchedule")(function* (directory) {
|
|
45308
|
+
if (yield* scheduleSettled(directory))
|
|
45309
|
+
return exports_Option.none();
|
|
45310
|
+
const scheduler = yield* hostScheduler.pipe(exports_Effect.option);
|
|
45311
|
+
const daily = exports_Option.isSome(scheduler) ? yield* scheduler.value.dailyJob : exports_Option.none();
|
|
45312
|
+
if (exports_Option.isSome(daily))
|
|
45313
|
+
yield* perform(daily.value.retime(defaultInterval)).pipe(exports_Effect.tapError(() => exports_Effect.ignore(perform(daily.value.undo))));
|
|
45314
|
+
yield* settleSchedule(directory);
|
|
45315
|
+
return exports_Option.map(exports_Option.all({ scheduler, daily }), ({ scheduler: scheduler2, daily: daily2 }) => ({
|
|
45316
|
+
scheduler: scheduler2.name,
|
|
45317
|
+
at: daily2.at,
|
|
45318
|
+
every: defaultInterval
|
|
45319
|
+
}));
|
|
45320
|
+
});
|
|
44234
45321
|
|
|
44235
45322
|
// packages/cli/src/copilot.ts
|
|
44236
45323
|
class CopilotError extends exports_Schema.TaggedError()("CopilotError", {
|
|
@@ -45181,21 +46268,21 @@ var getWidth = (string4) => {
|
|
|
45181
46268
|
return getStringWidth(plainText);
|
|
45182
46269
|
};
|
|
45183
46270
|
var getTokens = (string4) => {
|
|
45184
|
-
const
|
|
46271
|
+
const tokens2 = [];
|
|
45185
46272
|
forEachSegment(string4, (plainText) => {
|
|
45186
46273
|
if (ASCII_PRINTABLE_REGEX.test(plainText)) {
|
|
45187
46274
|
for (const character of plainText) {
|
|
45188
|
-
|
|
46275
|
+
tokens2.push({ value: character, width: 1 });
|
|
45189
46276
|
}
|
|
45190
46277
|
return;
|
|
45191
46278
|
}
|
|
45192
46279
|
for (const { segment } of segmenter2.segment(plainText)) {
|
|
45193
|
-
|
|
46280
|
+
tokens2.push({ value: segment, width: getStringWidth(segment) });
|
|
45194
46281
|
}
|
|
45195
46282
|
}, (escape2) => {
|
|
45196
|
-
|
|
46283
|
+
tokens2.push({ value: escape2, width: 0 });
|
|
45197
46284
|
});
|
|
45198
|
-
return
|
|
46285
|
+
return tokens2;
|
|
45199
46286
|
};
|
|
45200
46287
|
var splitWords = (string4) => {
|
|
45201
46288
|
let currentWord = { value: "", plainText: "" };
|
|
@@ -45386,17 +46473,17 @@ var applyLeadingSgrResets = (string4, startIndex, activeStyles) => {
|
|
|
45386
46473
|
var getClosingSgrSequence = (activeStyles) => [...activeStyles].reverse().map((activeStyle) => wrapAnsiCode(activeStyle.close)).join("");
|
|
45387
46474
|
var getOpeningSgrSequence = (activeStyles) => activeStyles.map((activeStyle) => wrapAnsiCode(activeStyle.open)).join("");
|
|
45388
46475
|
var wrapWord = (rows, word, columns, rowWidth) => {
|
|
45389
|
-
const
|
|
46476
|
+
const tokens2 = getTokens(word);
|
|
45390
46477
|
let visible = rowWidth;
|
|
45391
|
-
for (let index2 = 0;index2 <
|
|
45392
|
-
const token =
|
|
46478
|
+
for (let index2 = 0;index2 < tokens2.length; index2++) {
|
|
46479
|
+
const token = tokens2[index2];
|
|
45393
46480
|
if (token.width > 0 && visible > 0 && visible + token.width > columns) {
|
|
45394
46481
|
rows.push("");
|
|
45395
46482
|
visible = 0;
|
|
45396
46483
|
}
|
|
45397
46484
|
rows[rows.length - 1] += token.value;
|
|
45398
46485
|
visible += token.width;
|
|
45399
|
-
if (visible === columns && index2 <
|
|
46486
|
+
if (visible === columns && index2 < tokens2.length - 1) {
|
|
45400
46487
|
rows.push("");
|
|
45401
46488
|
visible = 0;
|
|
45402
46489
|
}
|
|
@@ -45593,6 +46680,242 @@ function wrapAnsi(string4, columns, options3) {
|
|
|
45593
46680
|
`);
|
|
45594
46681
|
}
|
|
45595
46682
|
|
|
46683
|
+
// packages/cli/src/upload.ts
|
|
46684
|
+
class SyncUnreachable extends exports_Schema.TaggedError()("SyncUnreachable", {
|
|
46685
|
+
message: exports_Schema.String
|
|
46686
|
+
}) {
|
|
46687
|
+
}
|
|
46688
|
+
|
|
46689
|
+
class SyncUnauthorized extends exports_Schema.TaggedError()("SyncUnauthorized", {
|
|
46690
|
+
status: exports_Schema.Number,
|
|
46691
|
+
message: exports_Schema.String
|
|
46692
|
+
}) {
|
|
46693
|
+
}
|
|
46694
|
+
|
|
46695
|
+
class SyncUnsupportedVersion extends exports_Schema.TaggedError()("SyncUnsupportedVersion", { message: exports_Schema.String }) {
|
|
46696
|
+
}
|
|
46697
|
+
|
|
46698
|
+
class SyncSuperseded extends exports_Schema.TaggedError()("SyncSuperseded", {
|
|
46699
|
+
message: exports_Schema.String
|
|
46700
|
+
}) {
|
|
46701
|
+
}
|
|
46702
|
+
|
|
46703
|
+
class SyncRejected extends exports_Schema.TaggedError()("SyncRejected", {
|
|
46704
|
+
status: exports_Schema.Number,
|
|
46705
|
+
message: exports_Schema.String
|
|
46706
|
+
}) {
|
|
46707
|
+
}
|
|
46708
|
+
var Acknowledgement = exports_Schema.Struct({ storedBuckets: exports_Schema.Natural });
|
|
46709
|
+
var MachineList = exports_Schema.Struct({
|
|
46710
|
+
staleAfterDays: exports_Schema.Number,
|
|
46711
|
+
from: exports_Schema.String,
|
|
46712
|
+
to: exports_Schema.String,
|
|
46713
|
+
machines: exports_Schema.Array(exports_Schema.Struct({ machineId: exports_Schema.String.check(exports_Schema.isUUID()) }))
|
|
46714
|
+
});
|
|
46715
|
+
function endpoint(server, path) {
|
|
46716
|
+
const base = new URL(server);
|
|
46717
|
+
base.pathname = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
|
|
46718
|
+
return new URL(path, base);
|
|
46719
|
+
}
|
|
46720
|
+
var VersionRejection = exports_Schema.Struct({ supportedVersions: exports_Schema.Array(exports_Schema.Int) });
|
|
46721
|
+
var readResponse = exports_Effect.fn("Sync.readResponse")(function* (response, version) {
|
|
46722
|
+
const status = response.status;
|
|
46723
|
+
if (status >= 200 && status < 300)
|
|
46724
|
+
return yield* exports_HttpClientResponse.schemaBodyJson(Acknowledgement)(response).pipe(exports_Effect.map((acknowledgement) => exports_Option.some(acknowledgement.storedBuckets)), exports_Effect.orElseSucceed(() => exports_Option.none()));
|
|
46725
|
+
if (status >= 500 || status === 408 || status === 429)
|
|
46726
|
+
return yield* new SyncUnreachable({
|
|
46727
|
+
message: `The server is temporarily unavailable (${status}); try again later.`
|
|
46728
|
+
});
|
|
46729
|
+
return yield* exports_Match.value(status).pipe(exports_Match.when(401, () => exports_Effect.fail(new SyncUnauthorized({
|
|
46730
|
+
status,
|
|
46731
|
+
message: "The server rejected the API token; create a new one in toki2."
|
|
46732
|
+
}))), exports_Match.when(403, () => exports_Effect.fail(new SyncUnauthorized({
|
|
46733
|
+
status,
|
|
46734
|
+
message: "This API token may not upload for this machine ID."
|
|
46735
|
+
}))), exports_Match.when(409, () => exports_Effect.fail(new SyncSuperseded({
|
|
46736
|
+
message: "Not stored: superseded by a newer sync from this machine. Run sync again to send this window; if every sync says this, check this machine's clock."
|
|
46737
|
+
}))), exports_Match.when(422, () => exports_HttpClientResponse.schemaBodyJson(VersionRejection)(response).pipe(exports_Effect.mapError(() => new SyncRejected({ status, message: `The server rejected the upload (${status}).` })), exports_Effect.flatMap((rejection) => exports_Effect.fail(rejection.supportedVersions.includes(version) ? new SyncRejected({ status, message: `The server rejected the upload (${status}).` }) : new SyncUnsupportedVersion({
|
|
46738
|
+
message: `The server accepts payload versions ${rejection.supportedVersions.join(", ") || "none"}, not ${version}; update Toki or use a compatible token-ledger version.`
|
|
46739
|
+
}))))), exports_Match.orElse(() => exports_Effect.fail(new SyncRejected({ status, message: `The server rejected the upload (${status}).` }))));
|
|
46740
|
+
});
|
|
46741
|
+
var upload = exports_Effect.fn("Sync.upload")(function* (server, token, payload) {
|
|
46742
|
+
const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
|
|
46743
|
+
const url = endpoint(server, `ai-usage/machines/${payload.machine.id}/usage`);
|
|
46744
|
+
const request3 = yield* exports_HttpClientRequest.put(url).pipe(exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson, exports_HttpClientRequest.schemaBodyJson(SyncPayload)(payload), exports_Effect.orDie);
|
|
46745
|
+
return yield* client.execute(request3).pipe(exports_Effect.flatMap((response) => readResponse(response, payload.version)), exports_Effect.scoped, exports_Effect.timeout("60 seconds"), exports_Effect.catchTag(["HttpClientError", "TimeoutError"], () => exports_Effect.fail(new SyncUnreachable({ message: `Cannot reach ${url.origin}; try again later.` }))), exports_Effect.retry({
|
|
46746
|
+
while: exports_Predicate.isTagged("SyncUnreachable"),
|
|
46747
|
+
schedule: exports_Schedule.exponential("2 seconds"),
|
|
46748
|
+
times: 3
|
|
46749
|
+
}));
|
|
46750
|
+
});
|
|
46751
|
+
var hasUploaded = exports_Effect.fn("Sync.hasUploaded")(function* (server, token, id2) {
|
|
46752
|
+
const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
|
|
46753
|
+
const url = endpoint(server, "ai-usage/machines");
|
|
46754
|
+
const unanswered = new SyncUnreachable({
|
|
46755
|
+
message: `Could not ask ${url.origin} whether this machine has uploaded before.`
|
|
46756
|
+
});
|
|
46757
|
+
return yield* client.execute(exports_HttpClientRequest.get(url).pipe(exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson)).pipe(exports_Effect.filterOrFail((response) => response.status === 200, () => unanswered), exports_Effect.flatMap(exports_HttpClientResponse.schemaBodyJson(MachineList)), exports_Effect.map(({ machines }) => machines.some((machine) => machine.machineId.toLowerCase() === id2.toLowerCase())), exports_Effect.scoped, exports_Effect.timeout("20 seconds"), exports_Effect.provideService(exports_FetchHttpClient.RequestInit, { redirect: "error" }), exports_Effect.mapError(() => unanswered));
|
|
46758
|
+
});
|
|
46759
|
+
|
|
46760
|
+
class RepricingUnavailable extends exports_Schema.TaggedError()("RepricingUnavailable", { message: exports_Schema.String }) {
|
|
46761
|
+
}
|
|
46762
|
+
|
|
46763
|
+
class RepricingRefused extends exports_Schema.TaggedError()("RepricingRefused", {
|
|
46764
|
+
status: exports_Schema.Number,
|
|
46765
|
+
message: exports_Schema.String
|
|
46766
|
+
}) {
|
|
46767
|
+
}
|
|
46768
|
+
var RepricingStatus = exports_Schema.Struct({
|
|
46769
|
+
floor: exports_Schema.DateTimeUtcFromString,
|
|
46770
|
+
providers: exports_Schema.Array(exports_Schema.Struct({
|
|
46771
|
+
provider: exports_Schema.String,
|
|
46772
|
+
from: exports_Schema.NullOr(exports_Schema.DateTimeUtcFromString),
|
|
46773
|
+
staleBuckets: exports_Schema.Natural
|
|
46774
|
+
}))
|
|
46775
|
+
});
|
|
46776
|
+
var RepricingReceipt = exports_Schema.Struct({
|
|
46777
|
+
updated: exports_Schema.Natural,
|
|
46778
|
+
unmatched: exports_Schema.Natural,
|
|
46779
|
+
beforeFloor: exports_Schema.Natural
|
|
46780
|
+
});
|
|
46781
|
+
function repricingAnswer(response, decode5) {
|
|
46782
|
+
const status = response.status;
|
|
46783
|
+
if (status >= 200 && status < 300)
|
|
46784
|
+
return decode5(response).pipe(exports_Effect.mapError(() => new RepricingRefused({ status, message: "The server's reply was not understood." })));
|
|
46785
|
+
if (status >= 500 || status === 408 || status === 429)
|
|
46786
|
+
return exports_Effect.fail(new RepricingUnavailable({ message: `The server is temporarily unavailable (${status}).` }));
|
|
46787
|
+
const message = exports_Match.value(status).pipe(exports_Match.when(401, () => "The server rejected the API token."), exports_Match.when(403, () => "This API token may not reprice for this machine ID."), exports_Match.when(404, () => "The server does not offer repricing; it may need an update."), exports_Match.orElse(() => `The server refused the request (${status}).`));
|
|
46788
|
+
return exports_Effect.fail(new RepricingRefused({ status, message }));
|
|
46789
|
+
}
|
|
46790
|
+
function exchange(server, request3, decode5, timeout4) {
|
|
46791
|
+
return exports_Effect.gen(function* () {
|
|
46792
|
+
const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
|
|
46793
|
+
return yield* client.execute(request3).pipe(exports_Effect.flatMap((response) => repricingAnswer(response, decode5)), exports_Effect.scoped, exports_Effect.timeout(timeout4), exports_Effect.catchTag(["HttpClientError", "TimeoutError"], () => exports_Effect.fail(new RepricingUnavailable({ message: `Cannot reach ${server.origin}.` }))), exports_Effect.retry({
|
|
46794
|
+
while: exports_Predicate.isTagged("RepricingUnavailable"),
|
|
46795
|
+
schedule: exports_Schedule.exponential("2 seconds"),
|
|
46796
|
+
times: 3
|
|
46797
|
+
}));
|
|
46798
|
+
});
|
|
46799
|
+
}
|
|
46800
|
+
var repricingStatus = exports_Effect.fn("Sync.repricingStatus")(function* (server, token, machineId, basis) {
|
|
46801
|
+
return yield* exchange(server, exports_HttpClientRequest.get(endpoint(server, `ai-usage/machines/${machineId}/repricing`)).pipe(exports_HttpClientRequest.setUrlParam("basis", basis), exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson), exports_HttpClientResponse.schemaBodyJson(RepricingStatus), "30 seconds");
|
|
46802
|
+
});
|
|
46803
|
+
var reprice = exports_Effect.fn("Sync.reprice")(function* (server, token, machineId, payload) {
|
|
46804
|
+
const request3 = yield* exports_HttpClientRequest.post(endpoint(server, `ai-usage/machines/${machineId}/repricing`)).pipe(exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson, exports_HttpClientRequest.schemaBodyJson(RepricePayload)(payload), exports_Effect.orDie);
|
|
46805
|
+
return yield* exchange(server, request3, exports_HttpClientResponse.schemaBodyJson(RepricingReceipt), "60 seconds");
|
|
46806
|
+
});
|
|
46807
|
+
|
|
46808
|
+
// packages/cli/src/reprice.ts
|
|
46809
|
+
var hour2 = 3600000;
|
|
46810
|
+
var isProvider = exports_Schema.is(Provider);
|
|
46811
|
+
var RepriceStep = exports_Data.taggedEnum();
|
|
46812
|
+
function repricePlan(status, scope3) {
|
|
46813
|
+
const floor = exports_DateTime.toEpochMillis(status.floor);
|
|
46814
|
+
return status.providers.flatMap((entry) => {
|
|
46815
|
+
const provider = entry.provider;
|
|
46816
|
+
if (!isProvider(provider) || !scope3.providers.has(provider) || entry.from === null)
|
|
46817
|
+
return [];
|
|
46818
|
+
const from = exports_DateTime.toEpochMillis(entry.from);
|
|
46819
|
+
const start = Math.ceil(Math.max(from, floor) / hour2) * hour2;
|
|
46820
|
+
if (start >= scope3.windowStart)
|
|
46821
|
+
return [];
|
|
46822
|
+
const finished = scope3.completed.some((completed) => completed.server === scope3.server && completed.provider === provider && completed.basis === scope3.basis && exports_DateTime.toEpochMillis(completed.from) === from && scope3.windowStart <= exports_DateTime.toEpochMillis(completed.coveredUntil));
|
|
46823
|
+
const staleBuckets = entry.staleBuckets;
|
|
46824
|
+
return [
|
|
46825
|
+
finished ? RepriceStep.Skip({ provider, from, staleBuckets }) : RepriceStep.Reprice({
|
|
46826
|
+
provider,
|
|
46827
|
+
from,
|
|
46828
|
+
range: { start, end: scope3.windowStart },
|
|
46829
|
+
staleBuckets
|
|
46830
|
+
})
|
|
46831
|
+
];
|
|
46832
|
+
});
|
|
46833
|
+
}
|
|
46834
|
+
var RepriceOutcome = exports_Data.taggedEnum();
|
|
46835
|
+
var repriceProvider = exports_Effect.fn("Sync.repriceProvider")(function* (run7, basis, step) {
|
|
46836
|
+
const { provider, from, staleBuckets } = step;
|
|
46837
|
+
let updated = 0;
|
|
46838
|
+
let unmatched = 0;
|
|
46839
|
+
let beforeFloor = 0;
|
|
46840
|
+
const failed = (message) => RepriceOutcome.Failed({ provider, from, message, updated, unmatched });
|
|
46841
|
+
const scanned = yield* run7.scan(provider, step.range).pipe(exports_Effect.result);
|
|
46842
|
+
if (exports_Result.isFailure(scanned))
|
|
46843
|
+
return failed(scanned.failure.message);
|
|
46844
|
+
const { buckets, coverage } = scanned.success;
|
|
46845
|
+
if (coverage.status === "failed")
|
|
46846
|
+
return failed("Some of its history could not be read.");
|
|
46847
|
+
if (coverage.status === "missing")
|
|
46848
|
+
return RepriceOutcome.NoHistory({ provider, from, staleBuckets });
|
|
46849
|
+
const { status, fetchedAt, source } = run7.payload.pricing;
|
|
46850
|
+
for (const chunk of repriceChunks(buckets)) {
|
|
46851
|
+
const payload = yield* RepricePayload.makeEffect({
|
|
46852
|
+
version: 1,
|
|
46853
|
+
clientVersion: run7.payload.clientVersion,
|
|
46854
|
+
pricing: { status, fetchedAt, source, basis },
|
|
46855
|
+
buckets: chunk
|
|
46856
|
+
}).pipe(exports_Effect.result);
|
|
46857
|
+
if (exports_Result.isFailure(payload))
|
|
46858
|
+
return failed("Its buckets do not satisfy the repricing contract.");
|
|
46859
|
+
const receipt = yield* reprice(run7.server, run7.token, run7.payload.machine.id, payload.success).pipe(exports_Effect.result);
|
|
46860
|
+
if (exports_Result.isFailure(receipt))
|
|
46861
|
+
return failed(receipt.failure.message);
|
|
46862
|
+
updated += receipt.success.updated;
|
|
46863
|
+
unmatched += receipt.success.unmatched;
|
|
46864
|
+
beforeFloor += receipt.success.beforeFloor;
|
|
46865
|
+
}
|
|
46866
|
+
return RepriceOutcome.Repriced({
|
|
46867
|
+
provider,
|
|
46868
|
+
from,
|
|
46869
|
+
staleBuckets,
|
|
46870
|
+
sent: buckets.length,
|
|
46871
|
+
updated,
|
|
46872
|
+
unmatched,
|
|
46873
|
+
beforeFloor
|
|
46874
|
+
});
|
|
46875
|
+
});
|
|
46876
|
+
var repriceStoredUsage = exports_Effect.fn("Sync.repriceStoredUsage")(function* (run7) {
|
|
46877
|
+
const basis = run7.payload.pricing.basis;
|
|
46878
|
+
if (basis === undefined)
|
|
46879
|
+
return [];
|
|
46880
|
+
const answer = yield* repricingStatus(run7.server, run7.token, run7.payload.machine.id, basis).pipe(exports_Effect.result);
|
|
46881
|
+
if (exports_Result.isFailure(answer))
|
|
46882
|
+
return [RepriceOutcome.Unanswered({ message: answer.failure.message })];
|
|
46883
|
+
const server = run7.server.origin;
|
|
46884
|
+
const completed = yield* loadRepricing(run7.directory);
|
|
46885
|
+
const steps = repricePlan(answer.success, {
|
|
46886
|
+
windowStart: Date.parse(run7.payload.window.start),
|
|
46887
|
+
providers: run7.providers,
|
|
46888
|
+
server,
|
|
46889
|
+
basis,
|
|
46890
|
+
completed
|
|
46891
|
+
});
|
|
46892
|
+
const outcomes = [];
|
|
46893
|
+
const finished = [];
|
|
46894
|
+
const coveredUntil = exports_DateTime.makeUnsafe(run7.payload.window.end);
|
|
46895
|
+
for (const step of steps) {
|
|
46896
|
+
const outcome = yield* RepriceStep.$match(step, {
|
|
46897
|
+
Skip: ({ provider, from, staleBuckets }) => exports_Effect.succeed(RepriceOutcome.Skipped({ provider, from, staleBuckets })),
|
|
46898
|
+
Reprice: (send) => repriceProvider(run7, basis, send)
|
|
46899
|
+
});
|
|
46900
|
+
outcomes.push(outcome);
|
|
46901
|
+
if (RepriceOutcome.$is("Repriced")(outcome))
|
|
46902
|
+
finished.push({
|
|
46903
|
+
server,
|
|
46904
|
+
provider: outcome.provider,
|
|
46905
|
+
basis,
|
|
46906
|
+
from: exports_DateTime.makeUnsafe(outcome.from),
|
|
46907
|
+
coveredUntil
|
|
46908
|
+
});
|
|
46909
|
+
}
|
|
46910
|
+
if (finished.length === 0)
|
|
46911
|
+
return outcomes;
|
|
46912
|
+
const kept = completed.filter((entry) => !finished.some((done4) => done4.server === entry.server && done4.provider === entry.provider));
|
|
46913
|
+
const saved = yield* saveRepricing(run7.directory, [...kept, ...finished]).pipe(exports_Effect.result);
|
|
46914
|
+
if (exports_Result.isFailure(saved))
|
|
46915
|
+
outcomes.push(RepriceOutcome.Unremembered({ message: saved.failure.message }));
|
|
46916
|
+
return outcomes;
|
|
46917
|
+
});
|
|
46918
|
+
|
|
45596
46919
|
// packages/cli/src/format.ts
|
|
45597
46920
|
function csvCell(value5) {
|
|
45598
46921
|
const text2 = value5 === null ? "" : String(value5);
|
|
@@ -45751,83 +47074,61 @@ function syncSummary(payload, request3, storedBuckets) {
|
|
|
45751
47074
|
].join(`
|
|
45752
47075
|
`);
|
|
45753
47076
|
}
|
|
45754
|
-
|
|
45755
|
-
|
|
45756
|
-
|
|
45757
|
-
|
|
45758
|
-
}
|
|
45759
|
-
|
|
45760
|
-
|
|
45761
|
-
|
|
45762
|
-
|
|
45763
|
-
|
|
45764
|
-
}) {
|
|
45765
|
-
|
|
45766
|
-
|
|
45767
|
-
|
|
45768
|
-
}
|
|
45769
|
-
|
|
45770
|
-
class SyncSuperseded extends exports_Schema.TaggedError()("SyncSuperseded", {
|
|
45771
|
-
message: exports_Schema.String
|
|
45772
|
-
}) {
|
|
45773
|
-
}
|
|
45774
|
-
|
|
45775
|
-
class SyncRejected extends exports_Schema.TaggedError()("SyncRejected", {
|
|
45776
|
-
status: exports_Schema.Number,
|
|
45777
|
-
message: exports_Schema.String
|
|
45778
|
-
}) {
|
|
47077
|
+
function unpricedModels(rows) {
|
|
47078
|
+
const counts = new Map;
|
|
47079
|
+
for (const row of rows)
|
|
47080
|
+
if (row.unpricedRecords > 0) {
|
|
47081
|
+
const name = `${terminalText(row.model)} (${row.provider}`;
|
|
47082
|
+
counts.set(name, (counts.get(name) ?? 0) + row.unpricedRecords);
|
|
47083
|
+
}
|
|
47084
|
+
if (counts.size === 0)
|
|
47085
|
+
return;
|
|
47086
|
+
const number4 = new Intl.NumberFormat("en-US");
|
|
47087
|
+
const ranked = [...counts].toSorted(([leftName, left], [rightName, right]) => right - left || leftName.localeCompare(rightName)).map(([name, records]) => `${name}, ${number4.format(records)} ${records === 1 ? "record" : "records"})`);
|
|
47088
|
+
const shown = ranked.slice(0, 5).join(", ");
|
|
47089
|
+
const more = ranked.length > 5 ? ` and ${ranked.length - 5} more` : "";
|
|
47090
|
+
return `Unpriced: ${shown}${more}. Configure their rates under "prices" to price them.`;
|
|
45779
47091
|
}
|
|
45780
|
-
|
|
45781
|
-
|
|
45782
|
-
staleAfterDays: exports_Schema.Number,
|
|
45783
|
-
from: exports_Schema.String,
|
|
45784
|
-
to: exports_Schema.String,
|
|
45785
|
-
machines: exports_Schema.Array(exports_Schema.Struct({ machineId: exports_Schema.String.check(exports_Schema.isUUID()) }))
|
|
45786
|
-
});
|
|
45787
|
-
function endpoint(server, path) {
|
|
45788
|
-
const base = new URL(server);
|
|
45789
|
-
base.pathname = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
|
|
45790
|
-
return new URL(path, base);
|
|
47092
|
+
function utcHour(instant) {
|
|
47093
|
+
return `${new Date(instant).toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
|
45791
47094
|
}
|
|
45792
|
-
|
|
45793
|
-
|
|
45794
|
-
const
|
|
45795
|
-
|
|
45796
|
-
|
|
45797
|
-
|
|
45798
|
-
|
|
45799
|
-
|
|
45800
|
-
|
|
45801
|
-
|
|
45802
|
-
|
|
45803
|
-
|
|
45804
|
-
|
|
45805
|
-
|
|
45806
|
-
|
|
45807
|
-
|
|
45808
|
-
|
|
45809
|
-
|
|
45810
|
-
|
|
45811
|
-
|
|
45812
|
-
})
|
|
45813
|
-
|
|
45814
|
-
|
|
45815
|
-
|
|
45816
|
-
|
|
45817
|
-
|
|
45818
|
-
|
|
45819
|
-
|
|
45820
|
-
|
|
45821
|
-
|
|
45822
|
-
})
|
|
45823
|
-
|
|
45824
|
-
|
|
45825
|
-
|
|
45826
|
-
|
|
45827
|
-
message: `Could not ask ${url.origin} whether this machine has uploaded before.`
|
|
47095
|
+
function repriceLine(outcome) {
|
|
47096
|
+
const number4 = new Intl.NumberFormat("en-US");
|
|
47097
|
+
const buckets = (count2) => `${number4.format(count2)} ${count2 === 1 ? "bucket" : "buckets"}`;
|
|
47098
|
+
return RepriceOutcome.$match(outcome, {
|
|
47099
|
+
Repriced: ({ provider, from, staleBuckets, sent, updated, unmatched, beforeFloor }) => ({
|
|
47100
|
+
text: [
|
|
47101
|
+
`Repriced ${provider} from ${utcHour(from)}`,
|
|
47102
|
+
`${buckets(staleBuckets)} stored on an older pricing basis`,
|
|
47103
|
+
`sent ${number4.format(sent)}`,
|
|
47104
|
+
`${number4.format(updated)} updated`,
|
|
47105
|
+
`${number4.format(unmatched)} unmatched`,
|
|
47106
|
+
...beforeFloor > 0 ? [`${number4.format(beforeFloor)} before the server's floor`] : []
|
|
47107
|
+
].join(" · "),
|
|
47108
|
+
problem: false
|
|
47109
|
+
}),
|
|
47110
|
+
Skipped: ({ provider, from, staleBuckets }) => ({
|
|
47111
|
+
text: `Repricing ${provider} skipped: this machine already sent its usage from ${utcHour(from)} on this pricing basis, and cannot reproduce the ${buckets(staleBuckets)} still stored on an older one.`,
|
|
47112
|
+
problem: false
|
|
47113
|
+
}),
|
|
47114
|
+
NoHistory: ({ provider, from, staleBuckets }) => ({
|
|
47115
|
+
text: `Repricing ${provider} from ${utcHour(from)} waits: this machine found no ${provider} history to rebuild the ${buckets(staleBuckets)} stored on an older pricing basis. The next sync looks again.`,
|
|
47116
|
+
problem: false
|
|
47117
|
+
}),
|
|
47118
|
+
Failed: ({ provider, from, message, updated, unmatched }) => ({
|
|
47119
|
+
text: `Repricing ${provider} from ${utcHour(from)} did not finish: ${message}${updated + unmatched > 0 ? ` Before that, ${number4.format(updated)} updated and ${number4.format(unmatched)} unmatched.` : ""} The next sync tries again.`,
|
|
47120
|
+
problem: true
|
|
47121
|
+
}),
|
|
47122
|
+
Unanswered: ({ message }) => ({
|
|
47123
|
+
text: `Could not ask the server what to reprice: ${message} The next sync asks again.`,
|
|
47124
|
+
problem: true
|
|
47125
|
+
}),
|
|
47126
|
+
Unremembered: ({ message }) => ({
|
|
47127
|
+
text: `${message} The next sync sends its reprices again.`,
|
|
47128
|
+
problem: true
|
|
47129
|
+
})
|
|
45828
47130
|
});
|
|
45829
|
-
|
|
45830
|
-
});
|
|
47131
|
+
}
|
|
45831
47132
|
|
|
45832
47133
|
// packages/cli/src/main.ts
|
|
45833
47134
|
class CliError2 extends exports_Schema.TaggedError()("CliError", { message: exports_Schema.String }) {
|
|
@@ -45843,7 +47144,15 @@ function usageFlags(sinceDefault, strict) {
|
|
|
45843
47144
|
since: exports_Flag.String("since").pipe(exports_Flag.withSchema(Day), exports_Flag.optional, exports_Flag.withDescription(`First local day, inclusive; defaults to ${sinceDefault}`)),
|
|
45844
47145
|
until: exports_Flag.String("until").pipe(exports_Flag.withSchema(Day), exports_Flag.optional, exports_Flag.withDescription("Last local day, inclusive; defaults to today")),
|
|
45845
47146
|
timeZone: exports_Flag.String("time-zone").pipe(exports_Flag.withSchema(exports_Schema.TimeZoneNamedFromString), exports_Flag.optional, exports_Flag.withDescription("IANA time zone for days and the window, such as Europe/Stockholm; defaults to the system zone")),
|
|
45846
|
-
provider: exports_Flag.Literals("provider", [
|
|
47147
|
+
provider: exports_Flag.Literals("provider", [
|
|
47148
|
+
"all",
|
|
47149
|
+
"codex",
|
|
47150
|
+
"claude",
|
|
47151
|
+
"grok",
|
|
47152
|
+
"copilot",
|
|
47153
|
+
"pi",
|
|
47154
|
+
"opencode"
|
|
47155
|
+
]).pipe(exports_Flag.withDefault("all")),
|
|
45847
47156
|
project: exports_Flag.String("project").pipe(exports_Flag.withSchema(ProjectName), exports_Flag.optional, exports_Flag.withDescription("Assign all selected usage to this project")),
|
|
45848
47157
|
config: exports_Flag.String("config").pipe(exports_Flag.optional, exports_Flag.withDescription("JSON config; otherwise reads ./token-ledger.json when present")),
|
|
45849
47158
|
offline: exports_Flag.Boolean("offline").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Use only cached and configured prices")),
|
|
@@ -45870,6 +47179,8 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
|
|
|
45870
47179
|
const copilotFile = yield* exports_Config.String("COPILOT_OTEL_FILE_EXPORTER_PATH").pipe(exports_Config.option);
|
|
45871
47180
|
const piHome = yield* exports_Config.String("PI_CODING_AGENT_DIR").pipe(exports_Config.withDefault(path.join(home, ".pi", "agent")));
|
|
45872
47181
|
const piSessions = yield* exports_Config.String("PI_CODING_AGENT_SESSION_DIR").pipe(exports_Config.option);
|
|
47182
|
+
const opencodeData = path.join(exports_Option.getOrElse(yield* dataHome, () => path.join(home, ".local", "share")), "opencode");
|
|
47183
|
+
const opencodeDatabase = exports_Option.map(exports_Option.filter(yield* exports_Config.String("OPENCODE_DB").pipe(exports_Config.option), (value5) => value5 !== "" && value5 !== ":memory:"), (value5) => path.resolve(opencodeData, value5));
|
|
45873
47184
|
const defaults2 = [
|
|
45874
47185
|
{ provider: "codex", path: path.join(expand(codexHome), "sessions") },
|
|
45875
47186
|
{ provider: "codex", path: path.join(expand(codexHome), "archived_sessions") },
|
|
@@ -45882,7 +47193,12 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
|
|
|
45882
47193
|
onNone: () => path.join(expand(piHome), "sessions"),
|
|
45883
47194
|
onSome: (value5) => expand(value5)
|
|
45884
47195
|
})
|
|
45885
|
-
}
|
|
47196
|
+
},
|
|
47197
|
+
{ provider: "opencode", path: opencodeData },
|
|
47198
|
+
...exports_Option.match(opencodeDatabase, {
|
|
47199
|
+
onNone: () => [],
|
|
47200
|
+
onSome: (file2) => path.dirname(file2) === opencodeData && opencodeDatabaseName.test(path.basename(file2)) ? [] : [{ provider: "opencode", path: file2 }]
|
|
47201
|
+
})
|
|
45886
47202
|
];
|
|
45887
47203
|
let sources = configuration.sources === undefined ? defaults2 : configuration.sources.map((source) => ({
|
|
45888
47204
|
...source,
|
|
@@ -45893,7 +47209,7 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
|
|
|
45893
47209
|
if (exports_Option.isSome(flags.source)) {
|
|
45894
47210
|
if (flags.provider === "all")
|
|
45895
47211
|
return yield* new CliError2({
|
|
45896
|
-
message: "--source requires --provider codex, claude, grok, copilot, or
|
|
47212
|
+
message: "--source requires --provider codex, claude, grok, copilot, pi, or opencode."
|
|
45897
47213
|
});
|
|
45898
47214
|
sources = [{ provider: flags.provider, path: expand(flags.source.value) }];
|
|
45899
47215
|
}
|
|
@@ -45910,13 +47226,8 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
|
|
|
45910
47226
|
paths: mapping.paths.map((prefix3) => expand(prefix3, path.dirname(configFile)))
|
|
45911
47227
|
}));
|
|
45912
47228
|
const cacheRoot = yield* exports_Config.String("XDG_CACHE_HOME").pipe(exports_Config.withDefault(path.join(home, ".cache")));
|
|
45913
|
-
const basePrices = yield* loadPrices(path.join(expand(cacheRoot), "token-ledger", "prices.json"), flags.offline);
|
|
45914
|
-
const pricing = configuration.prices
|
|
45915
|
-
...basePrices,
|
|
45916
|
-
status: "custom",
|
|
45917
|
-
source: `${basePrices.source}; configuration overrides`,
|
|
45918
|
-
prices: { ...basePrices.prices, ...configuration.prices }
|
|
45919
|
-
});
|
|
47229
|
+
const basePrices = yield* loadPrices(path.join(expand(cacheRoot), "token-ledger", "prices-v2.json"), flags.offline);
|
|
47230
|
+
const pricing = configuredPricing(basePrices, configuration.prices);
|
|
45920
47231
|
if (pricing.status === "unavailable")
|
|
45921
47232
|
yield* exports_Console.error("Pricing unavailable: unknown rates remain unpriced. Configure prices or rerun online.");
|
|
45922
47233
|
const request3 = yield* ReportRequest.makeEffect({
|
|
@@ -45951,6 +47262,9 @@ var report = exports_Command.make("report", {
|
|
|
45951
47262
|
if (source.status !== "ok" || source.warnings.length > 0)
|
|
45952
47263
|
yield* exports_Console.error(`${source.provider}: ${source.status}; ${source.files} files, ${source.filesBeforeWindow} older files not opened, ${source.malformedLines} malformed lines, ${source.skippedRecords} skipped records. ${source.warnings.join(" ")}`);
|
|
45953
47264
|
}
|
|
47265
|
+
const unpriced = unpricedModels(result6.rows);
|
|
47266
|
+
if (unpriced !== undefined)
|
|
47267
|
+
yield* exports_Console.error(unpriced);
|
|
45954
47268
|
if (flags.strict && (result6.coverage.some((entry) => entry.status !== "ok") || result6.rows.some((row) => row.unpricedRecords > 0)))
|
|
45955
47269
|
process.exitCode = 2;
|
|
45956
47270
|
})).pipe(exports_Command.withDescription("Report local token consumption and API-equivalent cost by project"));
|
|
@@ -45999,10 +47313,20 @@ var sync6 = exports_Command.make("sync", {
|
|
|
45999
47313
|
yield* exports_Console.error(`Warning: the window starts more than ${claudeRetentionDays} days ago. Claude Code deletes older transcripts by default, and the server replaces the whole window, so pruned history would lower its totals.`);
|
|
46000
47314
|
if (flags.dryRun) {
|
|
46001
47315
|
yield* exports_Console.log(JSON.stringify(first.payload, null, 2));
|
|
47316
|
+
const unpriced2 = unpricedModels(first.payload.buckets);
|
|
47317
|
+
if (unpriced2 !== undefined)
|
|
47318
|
+
yield* exports_Console.error(unpriced2);
|
|
46002
47319
|
if (flags.strict && incomplete)
|
|
46003
47320
|
process.exitCode = 2;
|
|
46004
47321
|
return;
|
|
46005
47322
|
}
|
|
47323
|
+
yield* retimeDailySchedule(directory).pipe(exports_Effect.matchEffect({
|
|
47324
|
+
onSuccess: exports_Option.match({
|
|
47325
|
+
onNone: () => exports_Effect.void,
|
|
47326
|
+
onSome: (retimed) => exports_Console.log(`Moved the scheduled sync from once a day at ${retimed.at} to ${describeTimes(retimed)}, as a ${retimed.scheduler}. To keep a daily sync, run token-ledger schedule install --every 24h.`)
|
|
47327
|
+
}),
|
|
47328
|
+
onFailure: (error2) => exports_Console.error(`Cannot move the once-a-day scheduled sync to every ${defaultInterval} hours: ${error2.message} Run token-ledger schedule install to replace it.`)
|
|
47329
|
+
}));
|
|
46006
47330
|
const refused = exports_Effect.gen(function* () {
|
|
46007
47331
|
yield* exports_Console.error("Not syncing: coverage is incomplete or usage is unpriced (--strict).");
|
|
46008
47332
|
process.exitCode = 2;
|
|
@@ -46039,7 +47363,20 @@ var sync6 = exports_Command.make("sync", {
|
|
|
46039
47363
|
process.exitCode = exports_Match.value(outcome.failure).pipe(exports_Match.tag("SyncUnreachable", () => 3), exports_Match.tag("SyncUnauthorized", () => 4), exports_Match.tag("SyncUnsupportedVersion", () => 5), exports_Match.tag("SyncRejected", () => 6), exports_Match.tag("SyncSuperseded", () => 7), exports_Match.exhaustive);
|
|
46040
47364
|
return;
|
|
46041
47365
|
}
|
|
47366
|
+
const unpriced = unpricedModels(sent.payload.buckets);
|
|
47367
|
+
if (unpriced !== undefined)
|
|
47368
|
+
yield* exports_Console.error(unpriced);
|
|
46042
47369
|
yield* exports_Console.log(syncSummary(sent.payload, { ...request3, since: sent.since }, outcome.success));
|
|
47370
|
+
const repriced = yield* repriceStoredUsage({
|
|
47371
|
+
server: server.value,
|
|
47372
|
+
token: token.value,
|
|
47373
|
+
payload: sent.payload,
|
|
47374
|
+
providers: new Set(request3.sources.map((source) => source.provider)),
|
|
47375
|
+
directory,
|
|
47376
|
+
scan: (provider, range3) => ledger.repriceBuckets(request3, provider, range3)
|
|
47377
|
+
});
|
|
47378
|
+
for (const { text: text2, problem } of repriced.map(repriceLine))
|
|
47379
|
+
yield* problem ? exports_Console.error(text2) : exports_Console.log(text2);
|
|
46043
47380
|
})).pipe(exports_Command.withDescription("Upload hourly usage buckets from this machine to toki2; the server replaces the window"));
|
|
46044
47381
|
var interactive = (prompt) => exports_Prompt.run(prompt).pipe(exports_Effect.mapError(() => new CliError2({
|
|
46045
47382
|
message: "Nothing was saved. Without a terminal, pass --server and set TOKI_API_TOKEN."
|
|
@@ -46064,11 +47401,19 @@ var login = exports_Command.make("login", {
|
|
|
46064
47401
|
Next: token-ledger sync --dry-run, then token-ledger schedule install.`);
|
|
46065
47402
|
})).pipe(exports_Command.withDescription("Save the toki2 server and API token in sync.json for sync and scheduled syncs"));
|
|
46066
47403
|
var scheduleInstall = exports_Command.make("install", {
|
|
46067
|
-
every: exports_Flag.ChoiceWithValue("every", intervals).pipe(exports_Flag.withDefault(
|
|
47404
|
+
every: exports_Flag.ChoiceWithValue("every", intervals).pipe(exports_Flag.withDefault(defaultInterval), exports_Flag.withDescription(`Time between syncs; defaults to ${defaultInterval}h`)),
|
|
46068
47405
|
at: exports_Flag.String("at").pipe(exports_Flag.withDefault("12:30"), exports_Flag.withSchema(TimeOfDay), exports_Flag.withDescription("A local time, as HH:MM, that a sync runs at; defaults to 12:30")),
|
|
46069
47406
|
config: exports_Flag.String("config").pipe(exports_Flag.optional, exports_Flag.withDescription("JSON config for the scheduled sync; ./token-ledger.json is not read")),
|
|
46070
47407
|
timeZone: exports_Flag.String("time-zone").pipe(exports_Flag.withSchema(exports_Schema.TimeZoneNamedFromString), exports_Flag.optional, exports_Flag.withDescription("IANA time zone for the scheduled sync; defaults to the system zone")),
|
|
46071
|
-
provider: exports_Flag.Literals("provider", [
|
|
47408
|
+
provider: exports_Flag.Literals("provider", [
|
|
47409
|
+
"all",
|
|
47410
|
+
"codex",
|
|
47411
|
+
"claude",
|
|
47412
|
+
"grok",
|
|
47413
|
+
"copilot",
|
|
47414
|
+
"pi",
|
|
47415
|
+
"opencode"
|
|
47416
|
+
]).pipe(exports_Flag.withDefault("all")),
|
|
46072
47417
|
dryRun: exports_Flag.Boolean("dry-run").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Print the files and commands; change nothing"))
|
|
46073
47418
|
}, exports_Effect.fn("CLI.scheduleInstall")(function* (flags) {
|
|
46074
47419
|
const fs = yield* exports_FileSystem.FileSystem;
|
|
@@ -46101,6 +47446,7 @@ var scheduleInstall = exports_Command.make("install", {
|
|
|
46101
47446
|
message: "No saved server and API token. Run token-ledger login first: a scheduled sync cannot read --token or your shell's environment."
|
|
46102
47447
|
});
|
|
46103
47448
|
yield* perform(actions);
|
|
47449
|
+
yield* settleSchedule(directory).pipe(exports_Effect.ignore);
|
|
46104
47450
|
yield* exports_Console.log(`Scheduled a sync ${describeTimes(flags)} as a ${scheduler.name}, replacing any earlier schedule. Inspect it with token-ledger schedule status.`);
|
|
46105
47451
|
})).pipe(exports_Command.withDescription("Install or replace the scheduled sync; it needs the server and token saved by login"));
|
|
46106
47452
|
var scheduleStatus = exports_Command.make("status", {}, exports_Effect.fn("CLI.scheduleStatus")(function* () {
|