codex-copilot-dx 1.3.25 → 1.3.26

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.
@@ -5,14 +5,15 @@ const DAYS = 365;
5
5
  const MAX_MODELS = 100;
6
6
  const TOKEN_FIELDS = ["input_tokens", "output_tokens", "total_tokens", "cached_input_tokens", "cache_read_input_tokens", "cache_write_input_tokens", "cache_hit_unknown_requests", "cache_hit_invalid_requests", "cache_hit_known_requests", "cache_hit_input_tokens", "cache_hit_read_tokens"];
7
7
 
8
- export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), qualifyProviders = false } = {}) {
8
+ export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), qualifyProviders = false, from: rangeFrom = "", to: rangeTo = "" } = {}) {
9
9
  const formatter = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
10
- const today = formatter.format(new Date(now));
10
+ const today = rangeTo || formatter.format(new Date(now));
11
11
  const end = Date.parse(`${today}T00:00:00Z`);
12
- const start = end - (DAYS - 1) * DAY_MS;
12
+ const start = Math.max(end - (DAYS - 1) * DAY_MS, rangeFrom ? Date.parse(rangeFrom) : -Infinity);
13
13
  const from = new Date(start).toISOString().slice(0, 10);
14
14
  const dates = new Map();
15
15
  const models = new Set();
16
+ const earlier = { requests: 0, byModel: new Map() };
16
17
  let first = Infinity;
17
18
  let last = -Infinity;
18
19
  let undated = 0;
@@ -38,6 +39,7 @@ export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), quali
38
39
  cache_hit_rate: usageCacheHitRate(values),
39
40
  cache_hit_known_requests: values.cache_hit_known_requests || 0,
40
41
  cache_hit_unknown_requests: values.cache_hit_unknown_requests || 0,
42
+ cache_hit_invalid_requests: values.cache_hit_invalid_requests || 0,
41
43
  cache_hit_input_tokens: values.cache_hit_input_tokens ?? null,
42
44
  cache_hit_read_tokens: values.cache_hit_read_tokens ?? null,
43
45
  cache_hit_rate_partial: values.cache_hit_unknown_requests > 0,
@@ -52,10 +54,9 @@ export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), quali
52
54
  if (!Number.isFinite(timestamp) || timestamp > now) { undated += 1; return; }
53
55
  first = Math.min(first, timestamp);
54
56
  last = Math.max(last, timestamp);
55
- if (timestamp < start - 2 * DAY_MS) return;
56
57
  const date = formatter.format(new Date(timestamp));
57
- if (date < from || date > today) return;
58
- let point = dates.get(date);
58
+ if (date > today) return;
59
+ let point = date < from ? earlier : dates.get(date);
59
60
  if (!point) { point = { requests: 0, byModel: new Map() }; dates.set(date, point); }
60
61
  add(point, summary.totals);
61
62
  const model = String(qualifyProviders ? `${usageProvider(record)} / ${record.model || "unknown"}` : record.model || "unknown").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 100);
@@ -66,7 +67,7 @@ export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), quali
66
67
  },
67
68
  snapshot() {
68
69
  const firstDate = Number.isFinite(first) ? formatter.format(new Date(first)) : null;
69
- const days = Array.from({ length: DAYS }, (_, index) => {
70
+ const days = Array.from({ length: Math.floor((end - start) / DAY_MS) + 1 }, (_, index) => {
70
71
  const date = new Date(start + index * DAY_MS).toISOString().slice(0, 10);
71
72
  const point = dates.get(date);
72
73
  return {
@@ -77,6 +78,7 @@ export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), quali
77
78
  };
78
79
  });
79
80
  return { time_zone: formatter.resolvedOptions().timeZone, from, to: today, first_date: firstDate,
81
+ ...(earlier.requests ? { earlier: { date: "earlier", before: from, available: true, ...row(earlier), models: [...earlier.byModel].map(([model, values]) => ({ model, ...row(values) })) } } : {}),
80
82
  last_date: Number.isFinite(last) ? formatter.format(new Date(last)) : null,
81
83
  undated_records: undated, models_truncated: modelsTruncated, models: [...models].sort(), days };
82
84
  },
@@ -0,0 +1,36 @@
1
+ import { isProviderId } from "./provider-metadata.mjs";
2
+ import { usageProvider } from "./usage-store.mjs";
3
+
4
+ const DAY_MS = 86400000;
5
+ const dateValue = value => /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(value))
6
+ && new Date(value).toISOString().slice(0, 10) === value;
7
+
8
+ export function createUsageQuery({ provider = "", model = "", days = "all", from = "", to = "", timeZone = "UTC", now = Date.now() } = {}) {
9
+ if (typeof provider !== "string" || provider && !isProviderId(provider)) throw new Error("Select a valid usage source");
10
+ if (typeof model !== "string" || model.length > 200 || /[\u0000-\u001f\u007f]/.test(model)) throw new Error("Select a valid usage model");
11
+ if (String(days) !== "all" && (!/^\d+$/.test(String(days)) || Number(days) < 1 || Number(days) > 365)) throw new Error("Usage days must be all or an integer from 1 to 365");
12
+ if (typeof timeZone !== "string" || timeZone.length > 100) throw new Error("Select a valid usage time zone");
13
+ const zone = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
14
+ const today = zone.format(new Date(now));
15
+ if (typeof from !== "string" || typeof to !== "string" || (from && !dateValue(from)) || (to && !dateValue(to))) throw new Error("Usage dates must use YYYY-MM-DD");
16
+ if ((from || to) && String(days) !== "all") throw new Error("Choose usage days or explicit dates");
17
+ if (String(days) !== "all") {
18
+ to = today;from = new Date(Date.parse(today) - (Number(days) - 1) * DAY_MS).toISOString().slice(0, 10);
19
+ }
20
+ if (from && !to) to = today;
21
+ if (from && to && from > to) throw new Error("Usage start date must not follow its end date");
22
+ const filters = { provider, model, days: String(days), from, to, time_zone: zone.resolvedOptions().timeZone };
23
+ return {
24
+ filters,
25
+ key: JSON.stringify(filters),
26
+ matches(record) {
27
+ if (provider && usageProvider(record) !== provider) return false;
28
+ if (model && model !== record.model && model !== `${usageProvider(record)} / ${record.model || "unknown"}`) return false;
29
+ if (!from && !to) return true;
30
+ const stamp = typeof record.ts === "string" ? Date.parse(record.ts) : NaN;
31
+ if (!Number.isFinite(stamp) || stamp > now) return false;
32
+ const date = zone.format(new Date(stamp));
33
+ return (!from || date >= from) && (!to || date <= to);
34
+ },
35
+ };
36
+ }
@@ -358,11 +358,12 @@ export function summarizeUsage(records, { provider = "" } = {}) {
358
358
  return summary;
359
359
  }
360
360
 
361
- async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord, provider = "" } = {}) {
361
+ async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord, recordFilter, provider = "" } = {}) {
362
362
  const summary = summarizeUsage([], { provider });
363
363
  for (const candidate of [rotatedFilePath(filePath), filePath]) {
364
364
  for await (const record of iterateUsageRecords(candidate, { warn })) {
365
365
  if (provider && provider !== usageProvider(record)) continue;
366
+ if (recordFilter && !recordFilter(record)) continue;
366
367
  const one = summarizeUsage([record]);
367
368
  onRecord?.(record, one);
368
369
  mergeUsageSummary(summary, one);
@@ -403,9 +404,9 @@ export async function usageSummaryVersion(filePath, { settled = true } = {}) {
403
404
  } catch { return null; } // Uncacheable metadata never replaces the normal read/error path.
404
405
  }
405
406
 
406
- export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord, provider = "", signal } = {}) {
407
+ export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord, recordFilter, provider = "", signal } = {}) {
407
408
  if (provider && !isProviderId(provider)) throw new Error("Usage provider must be a valid provider ID");
408
- if (onRecord || warn !== console.error) return summarizeUsageLogFiles(filePath, { warn, onRecord, provider });
409
+ if (onRecord || recordFilter || warn !== console.error) return summarizeUsageLogFiles(filePath, { warn, onRecord, recordFilter, provider });
409
410
  const fileVersion = await usageSummaryVersion(filePath);
410
411
  const version = fileVersion === null ? null : `${fileVersion}\0${provider}`;
411
412
  if (version === null) {
package/src/usage.mjs CHANGED
@@ -40,10 +40,14 @@ function cacheHitPercent(usage) {
40
40
  }
41
41
 
42
42
  function providerSummaryLines(summary) {
43
- if (summary.provider_filter) return [`Provider: ${terminalCell(summary.provider_filter)}`];
43
+ const filter = summary.filters, selection = filter ? [
44
+ ...(filter.model ? [`Model: ${terminalCell(filter.model)}`] : []),
45
+ ...(filter.from || filter.to ? [`Dates: ${filter.from || "earliest"} to ${filter.to || "latest"} (${terminalCell(filter.time_zone)})`] : []),
46
+ ] : [];
47
+ if (summary.provider_filter) return [`Provider: ${terminalCell(summary.provider_filter)}`, ...selection];
44
48
  const sources = Object.entries(summary.providers || {}).filter(([, count]) => count > 0);
45
- return sources.some(([id]) => id !== "github")
46
- ? [`Providers: ${sources.map(([id, count]) => `${terminalCell(id)} ${fmt(count)}`).join(" / ")} (combined totals; use --provider to separate)`] : [];
49
+ return [...(sources.some(([id]) => id !== "github")
50
+ ? [`Providers: ${sources.map(([id, count]) => `${terminalCell(id)} ${fmt(count)}`).join(" / ")} (combined totals; use --provider to separate)`] : []), ...selection];
47
51
  }
48
52
 
49
53
  function formatPlainUsageSummary(summary, filePath, { sanitize = false } = {}) {