@hasna/economy 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +4 -2
  3. package/dist/chunks/{billing-bkpxy4kv.js → billing-22az60hy.js} +2 -2
  4. package/dist/chunks/{config-j9mv3ehk.js → config-hsp7ndhj.js} +2 -2
  5. package/dist/chunks/{index-npsjjv96.js → index-9arv0b1j.js} +162 -36
  6. package/dist/chunks/{index-hesxq90g.js → index-9wa1f2kv.js} +1 -1
  7. package/dist/chunks/{index-zpvea08j.js → index-c7h2rxx1.js} +38 -12
  8. package/dist/chunks/{index-9d2aky06.js → index-ct3zdefz.js} +3 -3
  9. package/dist/chunks/{index-k540hfww.js → index-dk5rq1rq.js} +1 -1
  10. package/dist/chunks/{index-ez9thsr7.js → index-f5jv6q5q.js} +38 -12
  11. package/dist/chunks/{index-dj3tctqh.js → index-n1wwqxfe.js} +14 -13
  12. package/dist/chunks/{index-kzwqw3ve.js → index-nheq2nrz.js} +2 -2
  13. package/dist/chunks/{index-2hwzmfgv.js → index-vajzfzgv.js} +38 -12
  14. package/dist/chunks/{open-projects-6z4pq6mx.js → open-projects-8qm46m3d.js} +1 -1
  15. package/dist/chunks/{pricing-vf2pycmh.js → pricing-462f8xkm.js} +1 -1
  16. package/dist/chunks/{pricing-f80p81gr.js → pricing-k9wsjwbz.js} +1 -1
  17. package/dist/chunks/{pricing-y21mcjsa.js → pricing-vxejj1qa.js} +1 -1
  18. package/dist/chunks/{serve-p2yarhm8.js → serve-ra46ms69.js} +18 -10
  19. package/dist/chunks/{sqlite-store-st99garx.js → sqlite-store-13nhr1z0.js} +2 -2
  20. package/dist/chunks/{sqlite-store-501f32ts.js → sqlite-store-gamn65xp.js} +2 -2
  21. package/dist/chunks/{sqlite-store-fq4natnf.js → sqlite-store-ht6frztj.js} +2 -2
  22. package/dist/chunks/{tui-x64hjfrh.js → tui-a1tvcw2j.js} +4 -4
  23. package/dist/chunks/{watch-bxstjpbx.js → watch-rvd3dn6r.js} +5 -5
  24. package/dist/chunks/{webhooks-k4fh2t9c.js → webhooks-nw4daw9y.js} +20 -9
  25. package/dist/cli/index.js +27 -27
  26. package/dist/db/database.d.ts +2 -2
  27. package/dist/db/database.d.ts.map +1 -1
  28. package/dist/db/sync-pg.d.ts.map +1 -1
  29. package/dist/index.js +15 -14
  30. package/dist/lib/accounts-store.d.ts +25 -1
  31. package/dist/lib/accounts-store.d.ts.map +1 -1
  32. package/dist/lib/accounts.d.ts.map +1 -1
  33. package/dist/lib/analytics.d.ts +1 -1
  34. package/dist/lib/analytics.d.ts.map +1 -1
  35. package/dist/lib/periods.d.ts +20 -1
  36. package/dist/lib/periods.d.ts.map +1 -1
  37. package/dist/lib/spikes.d.ts +3 -3
  38. package/dist/lib/spikes.d.ts.map +1 -1
  39. package/dist/lib/subscriptions-registry.d.ts +26 -0
  40. package/dist/lib/subscriptions-registry.d.ts.map +1 -0
  41. package/dist/lib/test-keychain-fixture.d.ts +3 -2
  42. package/dist/lib/test-keychain-fixture.d.ts.map +1 -1
  43. package/dist/mcp/index.js +245 -118
  44. package/dist/otel/index.js +56 -27
  45. package/dist/server/index.js +246 -77
  46. package/dist/server/service-operations.d.ts.map +1 -1
  47. package/dist/server/service-worker.js +237 -68
  48. package/package.json +1 -1
@@ -4,12 +4,12 @@ import {
4
4
  } from "./index-w3bvv0ns.js";
5
5
  import {
6
6
  getStore
7
- } from "./index-9d2aky06.js";
7
+ } from "./index-ct3zdefz.js";
8
8
  import {
9
9
  formatReportedUsd,
10
10
  formatSummaryCoverage,
11
11
  formatSummaryValue
12
- } from "./index-ez9thsr7.js";
12
+ } from "./index-f5jv6q5q.js";
13
13
 
14
14
  // src/cli/commands/tui.ts
15
15
  import chalk from "chalk";
@@ -1064,12 +1064,32 @@ function meteredBudgetAmounts(groups, limit, threshold) {
1064
1064
  function ymd(date2) {
1065
1065
  return date2.toISOString().substring(0, 10);
1066
1066
  }
1067
- function calendarPeriodBounds(period, now = new Date) {
1067
+ function resolveReportingInterval(interval, now = new Date) {
1068
1068
  if (!Number.isFinite(now.getTime()))
1069
1069
  throw new RangeError("Invalid reporting clock");
1070
- const start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
1070
+ const start = new Date(now);
1071
+ start.setUTCHours(0, 0, 0, 0);
1071
1072
  const end = new Date(start);
1072
- switch (period) {
1073
+ if (interval.kind === "rolling") {
1074
+ if (!Number.isSafeInteger(interval.count) || interval.count < 1)
1075
+ throw new RangeError("Invalid reporting window");
1076
+ if (interval.unit === "hour") {
1077
+ start.setTime(now.getTime() - interval.count * 3600000);
1078
+ if (!Number.isFinite(start.getTime()))
1079
+ throw new RangeError("Invalid reporting window");
1080
+ return { time_zone: "UTC", start: start.toISOString(), end_exclusive: now.toISOString() };
1081
+ }
1082
+ if (interval.unit !== "day")
1083
+ throw new RangeError("Invalid reporting unit");
1084
+ start.setUTCDate(start.getUTCDate() - interval.count + 1);
1085
+ end.setUTCDate(end.getUTCDate() + 1);
1086
+ if (!Number.isFinite(start.getTime()) || !Number.isFinite(end.getTime()))
1087
+ throw new RangeError("Invalid reporting window");
1088
+ return { time_zone: "UTC", start: ymd(start), end_exclusive: ymd(end) };
1089
+ }
1090
+ if (interval.kind !== "calendar")
1091
+ throw new RangeError("Invalid reporting interval");
1092
+ switch (interval.period) {
1073
1093
  case "today":
1074
1094
  end.setUTCDate(end.getUTCDate() + 1);
1075
1095
  break;
@@ -1092,11 +1112,15 @@ function calendarPeriodBounds(period, now = new Date) {
1092
1112
  end.setUTCFullYear(end.getUTCFullYear() + 1);
1093
1113
  break;
1094
1114
  case "all":
1095
- return { time_zone: "UTC", start_date: null, end_date_exclusive: null };
1115
+ return { time_zone: "UTC", start: null, end_exclusive: null };
1096
1116
  default:
1097
1117
  throw new RangeError("Invalid reporting period");
1098
1118
  }
1099
- return { time_zone: "UTC", start_date: ymd(start), end_date_exclusive: ymd(end) };
1119
+ return { time_zone: "UTC", start: ymd(start), end_exclusive: ymd(end) };
1120
+ }
1121
+ function calendarPeriodBounds(period, now = new Date) {
1122
+ const bounds = resolveReportingInterval({ kind: "calendar", period }, now);
1123
+ return { time_zone: bounds.time_zone, start_date: bounds.start, end_date_exclusive: bounds.end_exclusive };
1100
1124
  }
1101
1125
  function calendarPeriodWhere(period, column, now = new Date) {
1102
1126
  if (!/^[a-z_][a-z0-9_]*(?:\.[a-z_][a-z0-9_]*)?$/i.test(column)) {
@@ -2485,20 +2509,22 @@ function queryAccountBreakdownSince(db, since) {
2485
2509
  ORDER BY api_equivalent_usd DESC
2486
2510
  `).all(since, since);
2487
2511
  }
2488
- function queryDailyBreakdown(db, days = 30, machine) {
2512
+ function queryDailyBreakdown(db, days = 30, machine, now = new Date) {
2513
+ const bounds = resolveReportingInterval({ kind: "rolling", unit: "day", count: days }, now);
2489
2514
  const machineClause = machine ? " AND machine_id = ?" : "";
2490
- const params = machine ? [`-${days}`, machine] : [`-${days}`];
2515
+ const params = machine ? [bounds.start, bounds.end_exclusive, machine] : [bounds.start, bounds.end_exclusive];
2491
2516
  return db.prepare(`
2492
2517
  SELECT DATE(timestamp) as date, agent, COALESCE(SUM(cost_usd), 0) as cost_usd
2493
2518
  FROM economy_effective_requests
2494
- WHERE timestamp >= DATE('now', ? || ' days')${machineClause}
2519
+ WHERE timestamp >= ? AND timestamp < ?${machineClause}
2495
2520
  GROUP BY DATE(timestamp), agent
2496
2521
  ORDER BY date ASC
2497
2522
  `).all(...params);
2498
2523
  }
2499
- function queryHourlyBreakdown(db, machine, hours) {
2500
- const clauses = hours == null ? [`DATE(timestamp) = DATE('now')`] : [`DATETIME(timestamp) >= DATETIME('now', ?)`];
2501
- const params = hours == null ? [] : [`-${hours} hours`];
2524
+ function queryHourlyBreakdown(db, machine, hours, now = new Date) {
2525
+ const bounds = resolveReportingInterval(hours == null ? { kind: "calendar", period: "today" } : { kind: "rolling", unit: "hour", count: hours }, now);
2526
+ const clauses = hours == null ? ["timestamp >= ? AND timestamp < ?"] : ["STRFTIME('%Y-%m-%dT%H:%M:%fZ', timestamp) >= ? AND STRFTIME('%Y-%m-%dT%H:%M:%fZ', timestamp) < ?"];
2527
+ const params = [bounds.start, bounds.end_exclusive];
2502
2528
  if (machine) {
2503
2529
  clauses.push("machine_id = ?");
2504
2530
  params.push(machine);
@@ -3404,4 +3430,4 @@ function computeCostWithPricing(model, pricing, inputTokens, outputTokens, cache
3404
3430
  return (inputTokens * effective.inputPer1M + outputTokens * effective.outputPer1M + cacheReadTokens * effective.cacheReadPer1M + cacheWriteTokens * effective.cacheWritePer1M + cacheWrite1hTokens * (effective.cacheWrite1hPer1M ?? effective.cacheWritePer1M) + cacheStorageTokenHours * (effective.cacheStoragePer1MHour ?? 0)) / 1e6;
3405
3431
  }
3406
3432
 
3407
- export { observationId, subscriptionId, scanReceiptId, AGENTS, MAX_INGEST_ROWS, MAX_INGEST_BYTES, stableJson, canonicalIngestBodyHash, validateIngest, calendarPeriodBounds, calendarPeriodWhere, usageSnapshotFilterForPeriod, sessionOverlapWhere, dataDir, cacheDir, getMachineId, getHomeDir, getResolverDataRoot, getLegacyDataRoot, adoptResolverDataRoot, getExactDataRoot, getDataDir, getDbPath, initSchema, upsertCostCenter, getCostCenter, upsertRequest, upsertSession, rollupSession, querySessions, queryTopSessions, querySummary, queryZeroCostTokenizedModels, queryModelBreakdown, queryAgentBreakdown, queryProjectBreakdown, queryAccountBreakdown, queryCostCenterBreakdown, queryProjectBreakdownSince, queryAgentBreakdownSince, queryModelBreakdownSince, queryAccountBreakdownSince, queryDailyBreakdown, queryHourlyBreakdown, upsertProject, getProject, listProjects, deleteProject, upsertBudget, listBudgets, deleteBudget, getBudgetStatuses, upsertGoal, deleteGoal, listGoals, getGoalStatuses, getIngestState, loadIngestState, setIngestState, queryRequestsSince, insertFeedback, upsertBillingDaily, clearBillingRange, queryBillingSummary, countBillingRecords, getSessionDetail, listMachines, upsertModelPricing, getModelPricing, listModelPricing, deleteModelPricing, seedModelPricing, upsertSubscription, listSubscriptions, deleteSubscription, upsertUsageSnapshot, upsertScanReceipt, queryScanReceipts, queryUsageSnapshots, listMachineRegistry, dedupeRequests, bulkIngest, DEFAULT_PRICING, normalizeModelName, ensurePricingSeeded, getPricingFromDb, getPricing, computeCost, computeCostFromDb, UnknownModelPricingError, assessCostFromDb, getPricingFromRows, estimateCostFromRows, assessCostFromRows, formatReportedUsd, formatPlanMoney, hasKnownUsagePrice, requireCurrentCostSummary, formatSummaryValue, formatSummaryCoverage, requireCurrentBillingSummary, formatBillingValue };
3433
+ export { observationId, subscriptionId, scanReceiptId, AGENTS, MAX_INGEST_ROWS, MAX_INGEST_BYTES, stableJson, canonicalIngestBodyHash, validateIngest, resolveReportingInterval, calendarPeriodBounds, calendarPeriodWhere, usageSnapshotFilterForPeriod, sessionOverlapWhere, dataDir, cacheDir, getMachineId, getHomeDir, getResolverDataRoot, getLegacyDataRoot, adoptResolverDataRoot, getExactDataRoot, getDataDir, getDbPath, initSchema, upsertCostCenter, getCostCenter, upsertRequest, upsertSession, rollupSession, querySessions, queryTopSessions, querySummary, queryZeroCostTokenizedModels, queryModelBreakdown, queryAgentBreakdown, queryProjectBreakdown, queryAccountBreakdown, queryCostCenterBreakdown, queryProjectBreakdownSince, queryAgentBreakdownSince, queryModelBreakdownSince, queryAccountBreakdownSince, queryDailyBreakdown, queryHourlyBreakdown, upsertProject, getProject, listProjects, deleteProject, upsertBudget, listBudgets, deleteBudget, getBudgetStatuses, upsertGoal, deleteGoal, listGoals, getGoalStatuses, getIngestState, loadIngestState, setIngestState, queryRequestsSince, insertFeedback, upsertBillingDaily, clearBillingRange, queryBillingSummary, countBillingRecords, getSessionDetail, listMachines, upsertModelPricing, getModelPricing, listModelPricing, deleteModelPricing, seedModelPricing, upsertSubscription, listSubscriptions, deleteSubscription, upsertUsageSnapshot, upsertScanReceipt, queryScanReceipts, queryUsageSnapshots, listMachineRegistry, dedupeRequests, bulkIngest, DEFAULT_PRICING, normalizeModelName, ensurePricingSeeded, getPricingFromDb, getPricing, computeCost, computeCostFromDb, UnknownModelPricingError, assessCostFromDb, getPricingFromRows, estimateCostFromRows, assessCostFromRows, formatReportedUsd, formatPlanMoney, hasKnownUsagePrice, requireCurrentCostSummary, formatSummaryValue, formatSummaryCoverage, requireCurrentBillingSummary, formatBillingValue };
@@ -1,7 +1,7 @@
1
1
  // @bun
2
2
  import {
3
3
  upsertProject
4
- } from "./index-ez9thsr7.js";
4
+ } from "./index-f5jv6q5q.js";
5
5
  import"./index-p35cyhc4.js";
6
6
 
7
7
  // src/lib/open-projects.ts
@@ -12,7 +12,7 @@ import {
12
12
  getPricingFromDb,
13
13
  getPricingFromRows,
14
14
  normalizeModelName
15
- } from "./index-2hwzmfgv.js";
15
+ } from "./index-f5jv6q5q.js";
16
16
  import"./index-p35cyhc4.js";
17
17
  export {
18
18
  normalizeModelName,
@@ -12,7 +12,7 @@ import {
12
12
  getPricingFromDb,
13
13
  getPricingFromRows,
14
14
  normalizeModelName
15
- } from "./index-zpvea08j.js";
15
+ } from "./index-c7h2rxx1.js";
16
16
  export {
17
17
  normalizeModelName,
18
18
  getPricingFromRows,
@@ -12,7 +12,7 @@ import {
12
12
  getPricingFromDb,
13
13
  getPricingFromRows,
14
14
  normalizeModelName
15
- } from "./index-ez9thsr7.js";
15
+ } from "./index-vajzfzgv.js";
16
16
  import"./index-p35cyhc4.js";
17
17
  export {
18
18
  normalizeModelName,
@@ -5,7 +5,7 @@ import {
5
5
  } from "./index-w3bvv0ns.js";
6
6
  import {
7
7
  syncAll
8
- } from "./index-npsjjv96.js";
8
+ } from "./index-9arv0b1j.js";
9
9
  import {
10
10
  buildBrief,
11
11
  packageMetadata,
@@ -16,7 +16,7 @@ import {
16
16
  queryProjectDetail,
17
17
  queryRangeStats,
18
18
  querySavingsSummary
19
- } from "./index-dj3tctqh.js";
19
+ } from "./index-n1wwqxfe.js";
20
20
  import {
21
21
  AGENTS,
22
22
  INGEST_SCHEMA_SQL,
@@ -59,6 +59,7 @@ import {
59
59
  queryTopSessions,
60
60
  queryUsageSnapshots,
61
61
  reconcileIngestReceipt,
62
+ resolveReportingInterval,
62
63
  subscriptionId,
63
64
  upsertBudget,
64
65
  upsertGoal,
@@ -66,7 +67,7 @@ import {
66
67
  upsertProject,
67
68
  upsertSubscription,
68
69
  usageSnapshotFilterForPeriod
69
- } from "./index-ez9thsr7.js";
70
+ } from "./index-f5jv6q5q.js";
70
71
  import {
71
72
  __require
72
73
  } from "./index-p35cyhc4.js";
@@ -133,15 +134,16 @@ function translateSqliteDates(sql) {
133
134
  s = s.replace(/DATE\('now',\s*(\$\d+)\s*\|\|\s*' days'\)/gi, (_m, p) => isoDate(`now() + ((${p}) || ' days')::interval`));
134
135
  s = s.replace(/DATETIME\('now',\s*(\$\d+)\)/gi, (_m, p) => `(now() + (${p})::interval)`);
135
136
  s = s.replace(/DATETIME\('now',\s*'([^']+)'\)/gi, (_m, lit) => `(now() + interval '${lit}')`);
137
+ s = s.replace(/STRFTIME\('%Y-%m-%dT%H:%M:%fZ',\s*([A-Za-z_][A-Za-z0-9_]*)\)/gi, (_m, col) => `to_char(CAST("${col}" AS timestamptz) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`);
136
138
  const strftimeMap = { "%H": "HH24", "%Y": "YYYY", "%m": "MM", "%d": "DD", "%M": "MI", "%S": "SS" };
137
139
  s = s.replace(/STRFTIME\('([^']+)',\s*([A-Za-z_][A-Za-z0-9_]*)\)/gi, (_m, fmt, col) => {
138
140
  const pgFmt = Object.entries(strftimeMap).reduce((acc, [k, v]) => acc.split(k).join(v), fmt);
139
- return `to_char(CAST("${col}" AS timestamptz), '${pgFmt}')`;
141
+ return `to_char(CAST("${col}" AS timestamptz) AT TIME ZONE 'UTC', '${pgFmt}')`;
140
142
  });
141
143
  s = s.replace(/\bDATE\('now'\)/gi, isoDate("now()"));
142
144
  s = s.replace(/\bDATETIME\('now'\)/gi, "now()");
143
145
  s = s.replace(/\bDATETIME\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)/gi, (_m, col) => `CAST("${col}" AS timestamptz)`);
144
- s = s.replace(/\bDATE\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)/gi, (_m, col) => `substr("${col}", 1, 10)`);
146
+ s = s.replace(/\bDATE\(\s*([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?)\s*\)/gi, (_m, col) => `substr(${col.split(".").map((part) => `"${part}"`).join(".")}, 1, 10)`);
145
147
  return s;
146
148
  }
147
149
  function resolveWorkerPath() {
@@ -3836,7 +3838,13 @@ function createDataHandler(db, actorId) {
3836
3838
  if (path === "/api/daily" && method === "GET") {
3837
3839
  const days = Number(url.searchParams.get("days") ?? 30);
3838
3840
  const machine = url.searchParams.get("machine") ?? undefined;
3839
- return ok(queryDailyBreakdown(db, days, machine));
3841
+ const now = new Date;
3842
+ try {
3843
+ resolveReportingInterval({ kind: "rolling", unit: "day", count: days }, now);
3844
+ } catch {
3845
+ return err("days must be a positive integer within the supported UTC date range");
3846
+ }
3847
+ return ok(queryDailyBreakdown(db, days, machine, now));
3840
3848
  }
3841
3849
  if (path === "/api/hourly" && method === "GET") {
3842
3850
  const machine = url.searchParams.get("machine") ?? undefined;
@@ -3902,7 +3910,7 @@ function createDataHandler(db, actorId) {
3902
3910
  if (providers.some((provider) => !allowedProviders.has(provider)))
3903
3911
  return err("invalid billing provider");
3904
3912
  const results = {};
3905
- const { syncAnthropicBilling, syncOpenAIBilling, syncGeminiBilling } = await import("./billing-bkpxy4kv.js");
3913
+ const { syncAnthropicBilling, syncOpenAIBilling, syncGeminiBilling } = await import("./billing-22az60hy.js");
3906
3914
  async function capture(provider, fn) {
3907
3915
  try {
3908
3916
  results[provider] = await fn();
@@ -4057,7 +4065,7 @@ function createDataHandler(db, actorId) {
4057
4065
  const results = {};
4058
4066
  if (sources === "all") {
4059
4067
  try {
4060
- const { syncOpenProjectsRegistry } = await import("./open-projects-6z4pq6mx.js");
4068
+ const { syncOpenProjectsRegistry } = await import("./open-projects-8qm46m3d.js");
4061
4069
  results["projects"] = await syncOpenProjectsRegistry(db);
4062
4070
  } catch {}
4063
4071
  }
@@ -4065,7 +4073,7 @@ function createDataHandler(db, actorId) {
4065
4073
  const syncResult = await syncAll(db, selected);
4066
4074
  Object.assign(results, syncResult);
4067
4075
  try {
4068
- const { checkAndFireWebhooks } = await import("./webhooks-k4fh2t9c.js");
4076
+ const { checkAndFireWebhooks } = await import("./webhooks-nw4daw9y.js");
4069
4077
  await checkAndFireWebhooks(db);
4070
4078
  } catch {}
4071
4079
  return ok(results);
@@ -4089,7 +4097,7 @@ function createDataHandler(db, actorId) {
4089
4097
  return err("invalid JSON body");
4090
4098
  const result = bulkIngest(db, body, { actorId });
4091
4099
  try {
4092
- const { checkAndFireWebhooks } = await import("./webhooks-k4fh2t9c.js");
4100
+ const { checkAndFireWebhooks } = await import("./webhooks-nw4daw9y.js");
4093
4101
  if (body["budget_mode"] !== "create")
4094
4102
  await checkAndFireWebhooks(db);
4095
4103
  } catch {}
@@ -69,7 +69,7 @@ import {
69
69
  upsertSession,
70
70
  upsertSubscription,
71
71
  upsertUsageSnapshot
72
- } from "./index-2hwzmfgv.js";
72
+ } from "./index-f5jv6q5q.js";
73
73
  import {
74
74
  __require
75
75
  } from "./index-p35cyhc4.js";
@@ -180,7 +180,7 @@ function openDatabase(dbPath, skipSeed = false) {
180
180
  }
181
181
  }, `opening ${path}`);
182
182
  if (!skipSeed) {
183
- import("./pricing-vf2pycmh.js").then(({ ensurePricingSeeded }) => ensurePricingSeeded(db)).catch(() => {});
183
+ import("./pricing-462f8xkm.js").then(({ ensurePricingSeeded }) => ensurePricingSeeded(db)).catch(() => {});
184
184
  }
185
185
  return db;
186
186
  }
@@ -69,7 +69,7 @@ import {
69
69
  upsertSession,
70
70
  upsertSubscription,
71
71
  upsertUsageSnapshot
72
- } from "./index-ez9thsr7.js";
72
+ } from "./index-vajzfzgv.js";
73
73
  import {
74
74
  __require
75
75
  } from "./index-p35cyhc4.js";
@@ -180,7 +180,7 @@ function openDatabase(dbPath, skipSeed = false) {
180
180
  }
181
181
  }, `opening ${path}`);
182
182
  if (!skipSeed) {
183
- import("./pricing-y21mcjsa.js").then(({ ensurePricingSeeded }) => ensurePricingSeeded(db)).catch(() => {});
183
+ import("./pricing-vxejj1qa.js").then(({ ensurePricingSeeded }) => ensurePricingSeeded(db)).catch(() => {});
184
184
  }
185
185
  return db;
186
186
  }
@@ -70,7 +70,7 @@ import {
70
70
  upsertSession,
71
71
  upsertSubscription,
72
72
  upsertUsageSnapshot
73
- } from "./index-zpvea08j.js";
73
+ } from "./index-c7h2rxx1.js";
74
74
 
75
75
  // src/db/sqlite-adapter.ts
76
76
  import { Database } from "bun:sqlite";
@@ -178,7 +178,7 @@ function openDatabase(dbPath, skipSeed = false) {
178
178
  }
179
179
  }, `opening ${path}`);
180
180
  if (!skipSeed) {
181
- import("./pricing-f80p81gr.js").then(({ ensurePricingSeeded }) => ensurePricingSeeded(db)).catch(() => {});
181
+ import("./pricing-k9wsjwbz.js").then(({ ensurePricingSeeded }) => ensurePricingSeeded(db)).catch(() => {});
182
182
  }
183
183
  return db;
184
184
  }
@@ -6,11 +6,11 @@ import {
6
6
  printStatusLine,
7
7
  printWaybarJson,
8
8
  runTui
9
- } from "./index-kzwqw3ve.js";
9
+ } from "./index-nheq2nrz.js";
10
10
  import"./index-w3bvv0ns.js";
11
- import"./index-9d2aky06.js";
12
- import"./index-dj3tctqh.js";
13
- import"./index-ez9thsr7.js";
11
+ import"./index-ct3zdefz.js";
12
+ import"./index-n1wwqxfe.js";
13
+ import"./index-f5jv6q5q.js";
14
14
  import"./index-p35cyhc4.js";
15
15
  export {
16
16
  runTui,
@@ -2,15 +2,15 @@
2
2
  import {
3
3
  agentPaths,
4
4
  syncAll
5
- } from "./index-npsjjv96.js";
5
+ } from "./index-9arv0b1j.js";
6
6
  import {
7
7
  getStore,
8
8
  isCloudStore
9
- } from "./index-9d2aky06.js";
10
- import"./index-dj3tctqh.js";
9
+ } from "./index-ct3zdefz.js";
10
+ import"./index-n1wwqxfe.js";
11
11
  import {
12
12
  formatSummaryValue
13
- } from "./index-ez9thsr7.js";
13
+ } from "./index-f5jv6q5q.js";
14
14
  import {
15
15
  __require
16
16
  } from "./index-p35cyhc4.js";
@@ -86,7 +86,7 @@ function agentLabel(agent) {
86
86
  async function watchCosts(opts) {
87
87
  const store = getStore();
88
88
  const cloud = isCloudStore();
89
- const db = cloud ? null : (await import("./sqlite-store-501f32ts.js")).openDatabase();
89
+ const db = cloud ? null : (await import("./sqlite-store-13nhr1z0.js")).openDatabase();
90
90
  let lastCheck = new Date(Date.now() - opts.interval * 1000).toISOString();
91
91
  const lines = [];
92
92
  const MAX_LINES = 20;
@@ -1,24 +1,34 @@
1
1
  // @bun
2
2
  import {
3
3
  loadConfig
4
- } from "./index-hesxq90g.js";
4
+ } from "./index-9wa1f2kv.js";
5
5
  import {
6
6
  getBudgetStatuses,
7
7
  getIngestState,
8
+ resolveReportingInterval,
8
9
  setIngestState
9
- } from "./index-ez9thsr7.js";
10
+ } from "./index-f5jv6q5q.js";
10
11
  import"./index-p35cyhc4.js";
11
12
 
12
13
  // src/lib/spikes.ts
13
14
  function detectCostSpikes(dailyTotals, opts) {
14
15
  const windowDays = opts?.windowDays ?? 7;
15
16
  const multiplier = opts?.multiplier ?? 2;
17
+ if (!Number.isSafeInteger(windowDays) || windowDays < 1)
18
+ throw new RangeError("Invalid spike window");
19
+ if (!Number.isFinite(multiplier) || multiplier <= 0)
20
+ throw new RangeError("Invalid spike multiplier");
16
21
  const sorted = [...dailyTotals].sort((a, b) => a.date.localeCompare(b.date));
17
22
  const spikes = [];
18
23
  for (let i = windowDays;i < sorted.length; i++) {
19
24
  const window = sorted.slice(i - windowDays, i);
20
- const avg = window.reduce((s, d) => s + d.cost_usd, 0) / window.length;
21
25
  const current = sorted[i];
26
+ const previous = new Date(current.date + "T00:00:00.000Z");
27
+ previous.setUTCDate(previous.getUTCDate() - 1);
28
+ const bounds = resolveReportingInterval({ kind: "rolling", unit: "day", count: windowDays }, previous);
29
+ if (window[0].date !== bounds.start || window[window.length - 1].date !== previous.toISOString().slice(0, 10) || new Set(window.map((day) => day.date)).size !== windowDays)
30
+ continue;
31
+ const avg = window.reduce((s, d) => s + d.cost_usd, 0) / window.length;
22
32
  if (avg > 0 && current.cost_usd > avg * multiplier) {
23
33
  spikes.push({
24
34
  date: current.date,
@@ -30,19 +40,20 @@ function detectCostSpikes(dailyTotals, opts) {
30
40
  }
31
41
  return spikes;
32
42
  }
33
- function queryRecentSpikes(db, days = 14) {
43
+ function queryRecentSpikes(db, days = 14, now = new Date) {
44
+ const bounds = resolveReportingInterval({ kind: "rolling", unit: "day", count: days }, now);
34
45
  const rows = db.prepare(`
35
46
  SELECT DATE(timestamp) as date, COALESCE(SUM(cost_usd), 0) as cost_usd
36
47
  FROM economy_effective_requests
37
- WHERE timestamp >= DATE('now', ? || ' days')
48
+ WHERE timestamp >= ? AND timestamp < ?
38
49
  GROUP BY DATE(timestamp)
39
50
  ORDER BY date ASC
40
- `).all(-days);
51
+ `).all(bounds.start, bounds.end_exclusive);
41
52
  return detectCostSpikes(rows);
42
53
  }
43
- function getTodaySpike(db) {
44
- const today = new Date().toISOString().substring(0, 10);
45
- const spikes = queryRecentSpikes(db, 14);
54
+ function getTodaySpike(db, now = new Date) {
55
+ const today = resolveReportingInterval({ kind: "calendar", period: "today" }, now).start;
56
+ const spikes = queryRecentSpikes(db, 14, now);
46
57
  return spikes.find((s) => s.date === today) ?? null;
47
58
  }
48
59
 
package/dist/cli/index.js CHANGED
@@ -4,26 +4,26 @@ import {
4
4
  syncAnthropicBilling,
5
5
  syncGeminiBilling,
6
6
  syncOpenAIBilling
7
- } from "../chunks/index-k540hfww.js";
7
+ } from "../chunks/index-dk5rq1rq.js";
8
8
  import {
9
9
  buildStatusLine,
10
10
  gatherStatusData
11
- } from "../chunks/index-kzwqw3ve.js";
11
+ } from "../chunks/index-nheq2nrz.js";
12
12
  import"../chunks/index-w3bvv0ns.js";
13
13
  import {
14
14
  agentPaths,
15
15
  syncAll
16
- } from "../chunks/index-npsjjv96.js";
16
+ } from "../chunks/index-9arv0b1j.js";
17
17
  import {
18
18
  getStore,
19
19
  isCloudStore
20
- } from "../chunks/index-9d2aky06.js";
20
+ } from "../chunks/index-ct3zdefz.js";
21
21
  import {
22
22
  billingDriftCheck,
23
23
  economyCloudStorage,
24
24
  economyTransportReport,
25
25
  packageMetadata
26
- } from "../chunks/index-dj3tctqh.js";
26
+ } from "../chunks/index-n1wwqxfe.js";
27
27
  import {
28
28
  AGENTS,
29
29
  MAX_INGEST_BYTES,
@@ -46,7 +46,7 @@ import {
46
46
  setIngestState,
47
47
  stableJson,
48
48
  validateIngest
49
- } from "../chunks/index-ez9thsr7.js";
49
+ } from "../chunks/index-f5jv6q5q.js";
50
50
  import {
51
51
  __require
52
52
  } from "../chunks/index-p35cyhc4.js";
@@ -1279,7 +1279,7 @@ function registerExtendedCommands(program) {
1279
1279
  }
1280
1280
  }
1281
1281
  if (!cloud) {
1282
- const { openDatabase } = await import("../chunks/sqlite-store-501f32ts.js");
1282
+ const { openDatabase } = await import("../chunks/sqlite-store-13nhr1z0.js");
1283
1283
  const db = openDatabase();
1284
1284
  ensurePricingSeeded(db);
1285
1285
  const zeroCostBuckets = queryZeroCostTokenizedModels(db, 5);
@@ -1357,23 +1357,23 @@ function registerExtendedCommands(program) {
1357
1357
  console.log();
1358
1358
  });
1359
1359
  program.command("tui").description("Terminal status dashboard (Linux/SSH friendly)").option("--watch", "Live refresh").option("--interval <seconds>", "Refresh interval", "30").action(async (opts) => {
1360
- const { runTui } = await import("../chunks/tui-x64hjfrh.js");
1360
+ const { runTui } = await import("../chunks/tui-a1tvcw2j.js");
1361
1361
  await runTui({
1362
1362
  watch: Boolean(opts.watch),
1363
1363
  interval: Number(opts.interval ?? 30)
1364
1364
  });
1365
1365
  });
1366
1366
  program.command("waybar").description("Print waybar-compatible JSON status line").action(async () => {
1367
- const { printWaybarJson } = await import("../chunks/tui-x64hjfrh.js");
1367
+ const { printWaybarJson } = await import("../chunks/tui-a1tvcw2j.js");
1368
1368
  await printWaybarJson();
1369
1369
  });
1370
1370
  const barCmd = program.command("bar").description("Status bar helpers (Linux)");
1371
1371
  barCmd.command("tui").description("Alias for economy tui").option("--watch", "Live refresh").action(async (opts) => {
1372
- const { runTui } = await import("../chunks/tui-x64hjfrh.js");
1372
+ const { runTui } = await import("../chunks/tui-a1tvcw2j.js");
1373
1373
  await runTui({ watch: Boolean(opts.watch) });
1374
1374
  });
1375
1375
  barCmd.command("waybar").description("Alias for economy waybar").action(async () => {
1376
- const { printWaybarJson } = await import("../chunks/tui-x64hjfrh.js");
1376
+ const { printWaybarJson } = await import("../chunks/tui-a1tvcw2j.js");
1377
1377
  await printWaybarJson();
1378
1378
  });
1379
1379
  program.command("estimate").description("Estimate cost for token counts").requiredOption("--model <model>", "Model name").option("--input <n>", "Input tokens", "0").option("--output <n>", "Output tokens", "0").action(async (opts) => {
@@ -2335,7 +2335,7 @@ function backfillMachineId(db) {
2335
2335
  return { requests: Number(reqCount.changes), sessions: Number(sessCount.changes) };
2336
2336
  }
2337
2337
  async function recalculateZeroCostRequests(db) {
2338
- const { assessCostFromDb } = await import("../chunks/pricing-y21mcjsa.js");
2338
+ const { assessCostFromDb } = await import("../chunks/pricing-462f8xkm.js");
2339
2339
  const zeroRows = db.prepare(`SELECT id, model, input_tokens, output_tokens, cache_read_tokens, cache_create_tokens, cache_create_5m_tokens, cache_create_1h_tokens
2340
2340
  FROM requests
2341
2341
  WHERE cost_usd = 0
@@ -2544,7 +2544,7 @@ async function postIngest(cloud, body) {
2544
2544
  }
2545
2545
  async function syncAllToCloud(cloud, opts = {}) {
2546
2546
  await runIngestJournalOperation(cloud, { action: "reconcile" });
2547
- const { openDatabase } = await import("../chunks/sqlite-store-501f32ts.js");
2547
+ const { openDatabase } = await import("../chunks/sqlite-store-13nhr1z0.js");
2548
2548
  const scratch = openDatabase(":memory:", true);
2549
2549
  ensurePricingSeeded(scratch);
2550
2550
  const cachePath = opts.cachePath ?? getIngestCachePath();
@@ -2571,7 +2571,7 @@ async function syncAllToCloud(cloud, opts = {}) {
2571
2571
  }
2572
2572
  async function billingSyncToCloud(cloud, opts = {}) {
2573
2573
  await runIngestJournalOperation(cloud, { action: "reconcile" });
2574
- const { openDatabase } = await import("../chunks/sqlite-store-501f32ts.js");
2574
+ const { openDatabase } = await import("../chunks/sqlite-store-13nhr1z0.js");
2575
2575
  const scratch = openDatabase(":memory:", true);
2576
2576
  try {
2577
2577
  const days = opts.days ?? 31;
@@ -2630,7 +2630,7 @@ function autosyncIntervalMs(env = process.env) {
2630
2630
  return Math.round(seconds * 1000);
2631
2631
  }
2632
2632
  async function autosyncMarkerStore(env = process.env) {
2633
- const { openDatabase } = await import("../chunks/sqlite-store-501f32ts.js");
2633
+ const { openDatabase } = await import("../chunks/sqlite-store-13nhr1z0.js");
2634
2634
  if (isCloudStore(env))
2635
2635
  return openDatabase(getIngestCachePath());
2636
2636
  return openDatabase();
@@ -2663,7 +2663,7 @@ async function autoSync(opts = {}) {
2663
2663
  return;
2664
2664
  if (!await autoSyncDue(undefined, process.env))
2665
2665
  return;
2666
- const { openDatabase } = await import("../chunks/sqlite-store-501f32ts.js");
2666
+ const { openDatabase } = await import("../chunks/sqlite-store-13nhr1z0.js");
2667
2667
  const db = openDatabase();
2668
2668
  ensurePricingSeeded(db);
2669
2669
  await syncAll(db, opts);
@@ -2931,13 +2931,13 @@ program.command("sync").description("Ingest cost data from all coding agents").o
2931
2931
  }
2932
2932
  return;
2933
2933
  }
2934
- const { openDatabase } = await import("../chunks/sqlite-store-501f32ts.js");
2934
+ const { openDatabase } = await import("../chunks/sqlite-store-13nhr1z0.js");
2935
2935
  const db = openDatabase();
2936
2936
  ensurePricingSeeded(db);
2937
2937
  const anySpecific = opts.claude || opts.takumi || opts.codex || opts.gemini || opts.opencode || opts.cursor || opts.pi || opts.hermes || opts.loops;
2938
2938
  if (!anySpecific || opts.verbose) {
2939
2939
  try {
2940
- const { syncOpenProjectsRegistry } = await import("../chunks/open-projects-6z4pq6mx.js");
2940
+ const { syncOpenProjectsRegistry } = await import("../chunks/open-projects-8qm46m3d.js");
2941
2941
  const p = await syncOpenProjectsRegistry(db);
2942
2942
  if (opts.verbose)
2943
2943
  console.log(chalk3.dim(`Synced open-projects registry: ${p.imported} imported, ${p.skipped} skipped`));
@@ -2972,7 +2972,7 @@ program.command("sync").description("Ingest cost data from all coding agents").o
2972
2972
  console.log(chalk3.cyan(`\u2192 Backfilled machine_id='${machine}': ${r.requests} requests, ${r.sessions} sessions`));
2973
2973
  }
2974
2974
  if (opts.recalculate) {
2975
- const { getPricingFromDb: getPricingFromDb2 } = await import("../chunks/pricing-y21mcjsa.js");
2975
+ const { getPricingFromDb: getPricingFromDb2 } = await import("../chunks/pricing-462f8xkm.js");
2976
2976
  const r = await recalculateZeroCostRequests(db);
2977
2977
  console.log(chalk3.cyan(`\u2192 Recalculated: ${r.fixed}/${r.total} zero-cost requests now have pricing`));
2978
2978
  const zeroCostBuckets = r.buckets;
@@ -2987,7 +2987,7 @@ program.command("sync").description("Ingest cost data from all coding agents").o
2987
2987
  }
2988
2988
  }
2989
2989
  try {
2990
- const { checkAndFireWebhooks } = await import("../chunks/webhooks-k4fh2t9c.js");
2990
+ const { checkAndFireWebhooks } = await import("../chunks/webhooks-nw4daw9y.js");
2991
2991
  await checkAndFireWebhooks(db);
2992
2992
  } catch {}
2993
2993
  for (const line of syncOutcomeLines(result))
@@ -3198,7 +3198,7 @@ program.command("accounts [period]").description("List account usage by email ad
3198
3198
  console.log();
3199
3199
  });
3200
3200
  program.command("watch").description("Live stream of incoming costs").option("--interval <seconds>", "Poll interval in seconds", "10").option("--daemon", "Watch agent data directories and sync on change").option("--agent <agent>", `Filter by agent (${AGENTS.join("|")})`).option("--notify <amount>", "Fire macOS notification when cumulative cost crosses this USD threshold").action(async (opts) => {
3201
- const { watchCosts } = await import("../chunks/watch-bxstjpbx.js");
3201
+ const { watchCosts } = await import("../chunks/watch-rvd3dn6r.js");
3202
3202
  await watchCosts({
3203
3203
  interval: parsePositiveCliInteger(opts.interval ?? "10", "--interval"),
3204
3204
  daemon: Boolean(opts.daemon),
@@ -3339,16 +3339,16 @@ projectCmd.command("show <nameOrPath>").description("Detailed project breakdown
3339
3339
  });
3340
3340
  var configCmd = program.command("config").description("Manage economy configuration");
3341
3341
  configCmd.command("set <key> <value>").description("Set a config value").action(async (_key, _value) => {
3342
- const { setConfigValue } = await import("../chunks/config-j9mv3ehk.js");
3342
+ const { setConfigValue } = await import("../chunks/config-hsp7ndhj.js");
3343
3343
  setConfigValue(_key, _value);
3344
3344
  console.log(chalk3.green(`\u2713 ${_key} = ${_value}`));
3345
3345
  });
3346
3346
  configCmd.command("get <key>").description("Get a config value").action(async (key) => {
3347
- const { getConfigValue } = await import("../chunks/config-j9mv3ehk.js");
3347
+ const { getConfigValue } = await import("../chunks/config-hsp7ndhj.js");
3348
3348
  console.log(getConfigValue(key) ?? chalk3.dim("(not set)"));
3349
3349
  });
3350
3350
  configCmd.command("webhook-test").description("Send a test payload to the configured webhook URL").action(async () => {
3351
- const { loadConfig } = await import("../chunks/config-j9mv3ehk.js");
3351
+ const { loadConfig } = await import("../chunks/config-hsp7ndhj.js");
3352
3352
  const config = loadConfig();
3353
3353
  const url = config["webhook-url"];
3354
3354
  if (!url) {
@@ -3382,7 +3382,7 @@ configCmd.command("webhook-test").description("Send a test payload to the config
3382
3382
  }
3383
3383
  });
3384
3384
  configCmd.action(async () => {
3385
- const { loadConfig } = await import("../chunks/config-j9mv3ehk.js");
3385
+ const { loadConfig } = await import("../chunks/config-hsp7ndhj.js");
3386
3386
  const config = loadConfig();
3387
3387
  console.log();
3388
3388
  printTable(["Key", "Value"], Object.entries(config).map(([k, v]) => [k, String(v)]));
@@ -3434,7 +3434,7 @@ pricingCmd.command("remove <model>").description("Remove pricing for a model").a
3434
3434
  });
3435
3435
  program.command("serve").description("Start the REST API server").option("-p, --port <port>", "Port", "3456").action(async (opts) => {
3436
3436
  const port = parseCliPort(opts.port ?? "3456", "--port");
3437
- const { startServer } = await import("../chunks/serve-p2yarhm8.js");
3437
+ const { startServer } = await import("../chunks/serve-ra46ms69.js");
3438
3438
  startServer(port);
3439
3439
  });
3440
3440
  program.command("mcp").description("Show MCP server install commands").option("--claude", "Install into Claude Code").option("--codex", "Install into Codex").option("--gemini", "Install into Gemini CLI").option("--all", "Install into all agents").action(async (opts) => {
@@ -3795,7 +3795,7 @@ billingCmd.command("sync").description("Sync actual billing from Anthropic, Open
3795
3795
  console.log(chalk3.green(`\u2713 pushed ${result.total} billing rows to the shared API`));
3796
3796
  return;
3797
3797
  }
3798
- const { openDatabase } = await import("../chunks/sqlite-store-501f32ts.js");
3798
+ const { openDatabase } = await import("../chunks/sqlite-store-13nhr1z0.js");
3799
3799
  const db = openDatabase();
3800
3800
  const doAll = !opts.anthropic && !opts.openai && !opts.gemini;
3801
3801
  if (opts.anthropic || doAll) {
@@ -77,12 +77,12 @@ export declare function queryProjectBreakdownSince(db: Database, since: string,
77
77
  export declare function queryAgentBreakdownSince(db: Database, since: string): AgentBreakdown[];
78
78
  export declare function queryModelBreakdownSince(db: Database, since: string): ModelBreakdown[];
79
79
  export declare function queryAccountBreakdownSince(db: Database, since: string): AccountBreakdown[];
80
- export declare function queryDailyBreakdown(db: Database, days?: number, machine?: string): Array<{
80
+ export declare function queryDailyBreakdown(db: Database, days?: number, machine?: string, now?: Date): Array<{
81
81
  date: string;
82
82
  cost_usd: number;
83
83
  agent: string;
84
84
  }>;
85
- export declare function queryHourlyBreakdown(db: Database, machine?: string, hours?: number): Array<{
85
+ export declare function queryHourlyBreakdown(db: Database, machine?: string, hours?: number, now?: Date): Array<{
86
86
  hour: string;
87
87
  cost_usd: number;
88
88
  agent: string;