codex-copilot-dx 1.3.24 → 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.
@@ -7,7 +7,7 @@
7
7
  }).join(" ");
8
8
  }
9
9
 
10
- function create({ time, element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator, modelLabel = value => value, motionAllowed = () => false }) {
10
+ function create({ time, element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator, modelLabel = value => value, usageChanged = () => {}, motionAllowed = () => false }) {
11
11
  function usageValues(row) {
12
12
  const rate = Number.isFinite(row.cache_hit_rate) && row.cache_hit_rate >= 0 && row.cache_hit_rate <= 1
13
13
  ? `${row.cache_hit_rate_partial ? "~" : ""}${(row.cache_hit_rate * 100).toFixed(1)}%` : "—";
@@ -17,6 +17,7 @@
17
17
  let usageData = null;
18
18
  let analyticsSignature, calendarSignature;
19
19
  let selectedUsageDate = "";
20
+ let previousRange = "all";
20
21
  let dailySignature, dailySelection, chartVisible = false, motionPending = false;
21
22
  let motionTargets = [];
22
23
  const animations = new Set();
@@ -103,18 +104,20 @@
103
104
  }
104
105
 
105
106
  function renderUsageTable() {
106
- const day = selectedUsageDate && usageData.analytics?.days.find((entry) => entry.date === selectedUsageDate);
107
+ const day = !usageData.filters && selectedUsageDate && usageData.analytics?.days.find((entry) => entry.date === selectedUsageDate);
107
108
  const model = element("analytics-model").value;
108
109
  const total = day ? { ...analyticsPoint(day, model), model: "TOTAL" } : usageData.total;
109
110
  const rows = day ? day.models.filter((row) => !model || row.model === model).sort((a, b) => b.total_tokens - a.total_tokens || a.model.localeCompare(b.model)) : usageData.rows;
110
111
  const body = element("usage-body");
111
112
  body.replaceChildren();
112
113
  if (total.requests > 0) {
113
- body.append(tableRow(usageValues(total), { total: true }));
114
- for (const row of rows) body.append(tableRow(usageValues(row)));
115
- } else { emptyTable("usage-body", 8, "no_usage_records"); }
116
- element("clear-usage-day").hidden = !day;
117
- text("usage-state", day ? day.date : "local_log");
114
+ for (const [index, row] of [total, ...rows].entries()) {
115
+ const entry = tableRow(usageValues(row), { total: index === 0 });
116
+ localize(entry.children[7], "usage_cache_coverage", { known: number(row.cache_hit_known_requests), unknown: number(row.cache_hit_unknown_requests) }, "title");body.append(entry);
117
+ }
118
+ } else { emptyTable("usage-body", 8, usageData.filters ? "usage_empty_selection" : "no_usage_records"); }
119
+ element("clear-usage-day").hidden = !selectedUsageDate;
120
+ renderUsageState();
118
121
  text("usage-note", "records_records_shown_of_models_models_shown_day", {
119
122
  records: number(total.requests), shown: number(rows.length), models: number(day ? rows.length : usageData.model_count),
120
123
  day: day ? phrase("zone_model", { zone: usageData.analytics.time_zone, model: model ? modelLabel(model) : phrase("all_models") }) : "",
@@ -122,17 +125,29 @@
122
125
  }
123
126
 
124
127
  function renderUsageState() {
125
- text("usage-state", selectedUsageDate && usageData.analytics?.days.some(day => day.date === selectedUsageDate) ? selectedUsageDate : "local_log");
128
+ if (selectedUsageDate.startsWith("<")) text("usage-state", "usage_earlier_before", { date: selectedUsageDate.slice(1) });
129
+ else text("usage-state", selectedUsageDate || "local_log");
126
130
  }
127
131
 
128
132
  function analyticsPoint(day, model) {
133
+ if (usageData?.filters) return day;
129
134
  return model ? day.models.find((row) => row.model === model) || { requests: 0, input_tokens: 0, output_tokens: 0 } : day;
130
135
  }
131
136
 
132
- function selectUsageDay(date) {
137
+ function selectUsageDay(date, { refresh = true } = {}) {
138
+ const select = element("analytics-range");
139
+ const hadDate = Boolean(selectedUsageDate);
140
+ if (date && !selectedUsageDate) previousRange = select.value;
133
141
  selectedUsageDate = date;
142
+ for (const option of [...select.children]) if (option.value === "date") option.remove();
143
+ if (date) {
144
+ const option = document.createElement("option");option.value = "date";
145
+ if (date.startsWith("<")) localize(option, "usage_earlier_before", { date: date.slice(1) });else option.textContent = date;
146
+ select.append(option);select.value = "date";
147
+ } else if (hadDate) select.value = previousRange;
134
148
  renderUsageTable();
135
149
  renderAnalytics();
150
+ if (refresh) usageChanged();
136
151
  }
137
152
 
138
153
  function dayButton(day, point) {
@@ -142,10 +157,10 @@
142
157
  button.setAttribute("aria-pressed", String(day.date === selectedUsageDate));
143
158
  const description = !day.available ? phrase("no_retained_history")
144
159
  : phrase("calls_recorded_calls_input_input_output_output_cached_cached_inc", {
145
- calls: number(point.requests), input: number(point.input_tokens), output: number(point.output_tokens), cached: number(point.cache_read_tokens), partial: point.tokens_partial ? phrase("partial_token_counts") : "",
160
+ calls: number(point.requests), input: number(point.input_tokens), output: number(point.output_tokens), cached: number(point.cache_read_tokens), partial: point.tokens_partial ? phrase("partial_token_counts") : "",
146
161
  });
147
- for (const attribute of ["title", "aria-label"]) localize(button, "date_description", { date: day.date, description }, attribute);
148
- button.addEventListener("click", () => selectUsageDay(day.date));
162
+ for (const attribute of ["title", "aria-label"]) localize(button, "date_description", { date: day.date === "earlier" ? phrase("usage_earlier_before", { date: day.before }) : day.date, description }, attribute);
163
+ button.addEventListener("click", () => selectUsageDay(day.date === "earlier" ? "<" + day.before : day.date));
149
164
  return button;
150
165
  }
151
166
 
@@ -158,13 +173,14 @@
158
173
  if (signature === analyticsSignature) return;
159
174
  analyticsSignature = signature;
160
175
  const days = analytics.days;
161
- const daily = days.slice(-Number(element("analytics-range").value));
176
+ const range = element("analytics-range").value === "date" ? previousRange : element("analytics-range").value;
177
+ const daily = usageData.filters ? [...(analytics.earlier ? [analytics.earlier] : []), ...days] : range === "all" ? days : days.slice(-Number(range));
162
178
  const maximum = Math.max(1, ...daily.map((day) => {
163
179
  const point = analyticsPoint(day, model);
164
180
  return point.input_tokens + point.output_tokens;
165
181
  }));
166
182
  renderDaily(daily, model, maximum);
167
- text("daily-from", daily[0].date);
183
+ text("daily-from", daily[0].date === "earlier" ? "usage_earlier" : daily[0].date);
168
184
  text("daily-to", analytics.to);
169
185
  if (commonSignature === calendarSignature) return;
170
186
  calendarSignature = commonSignature;
@@ -174,7 +190,7 @@
174
190
  return metric === "tokens" ? point.input_tokens + point.output_tokens : point.requests;
175
191
  };
176
192
  const peak = Math.max(1, ...days.map(value));
177
- text("activity-scale", "metric_peak_peak", { metric: phrase(metric === "tokens" ? "input_output" : "recorded_calls"), peak: number(peak === 1 && days.every((day) => value(day) === 0) ? 0 : peak) });
193
+ text("activity-scale", "metric_peak_peak", { metric: phrase(metric === "tokens" ? "input_output" : "recorded_usage"), peak: number(peak === 1 && days.every((day) => value(day) === 0) ? 0 : peak) });
178
194
  const calendar = element("activity-calendar");
179
195
  calendar.replaceChildren();
180
196
  const offset = (new Date(`${days[0].date}T00:00:00Z`).getUTCDay() + 6) % 7;
@@ -205,7 +221,7 @@
205
221
  calendar.append(button);
206
222
  }
207
223
  text("analytics-note", "zone_from_to_retained_history_starts_first_oldest_day_may_be_par", {
208
- zone: analytics.time_zone, from: daily[0].date, to: analytics.to, first: analytics.first_date || phrase("unknown"),
224
+ zone: analytics.time_zone, from: analytics.earlier ? analytics.first_date : daily[0].date, to: analytics.to, first: analytics.first_date || phrase("unknown"),
209
225
  excluded: analytics.undated_records ? phrase("count_records_with_invalid_future_timestamps_excluded", { count: number(analytics.undated_records) }) : "",
210
226
  limit: analytics.models_truncated ? phrase("model_filters_limited_to_100_all_model_totals_include_the_remain") : "",
211
227
  });
@@ -216,7 +232,7 @@
216
232
  const select = element("analytics-model");
217
233
  const previous = select.value;
218
234
  select.replaceChildren();
219
- for (const model of [...new Set(["", ...usageData.analytics.models, ...(previous ? [previous] : [])])]) {
235
+ for (const model of [...new Set(["", ...(usageData.available_models || usageData.analytics?.models || []), ...(previous ? [previous] : [])])]) {
220
236
  const option = document.createElement("option");
221
237
  option.value = model;
222
238
  if (model) option.textContent = modelLabel(model);
@@ -228,10 +244,10 @@
228
244
 
229
245
  function applyUsage(data, { changed }) {
230
246
  const sameProvider = (data.provider || "all") === (usageData?.provider || "all");
231
- if (!sameProvider) selectedUsageDate = "";
247
+ if (!sameProvider && selectedUsageDate) selectUsageDay("", { refresh: false });
232
248
  usageData = { ...data, ...(!data.analytics && sameProvider && usageData?.analytics ? { analytics: usageData.analytics } : {}) };
233
249
  if (changed) {
234
- if (data.analytics) updateAnalyticsModels();
250
+ if (data.available_models || data.analytics) updateAnalyticsModels();
235
251
  renderUsageTable();
236
252
  if (data.analytics) renderAnalytics();
237
253
  }
@@ -14,9 +14,10 @@ import {
14
14
  renderTerminalAnimationFrame,
15
15
  TERMINAL_ANIMATION_THEMES,
16
16
  } from "./terminal-animation.mjs";
17
- import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageModelGroups } from "./usage-store.mjs";
17
+ import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageModelGroups, usageProvider } from "./usage-store.mjs";
18
18
  import { createUsageAnalytics } from "./usage-analytics.mjs";
19
19
  import { analyzeUsageLogs } from "./usage-analysis.mjs";
20
+ import { createUsageQuery } from "./usage-query.mjs";
20
21
  import { readUserSettings, terminalAnimationPreference, writeTerminalAnimationTheme } from "./user-settings.mjs";
21
22
  import { settingsPreferencesSnapshot } from "./settings-preferences.mjs";
22
23
 
@@ -383,12 +384,15 @@ export async function handleDashboardApi(req, res, pathname, {
383
384
  const query = new URL(req.url, "http://localhost").searchParams;
384
385
  const provider = query.get("provider") || "";
385
386
  if (provider && !isProviderId(provider)) { sendJson(res, 400, { error: "Select a valid provider" });return; }
387
+ let selection;
388
+ try { selection = createUsageQuery({ provider, model: query.get("model") || "", days: query.get("days") || "all", from: query.get("from") || "", to: query.get("to") || "", timeZone: query.get("time_zone") || "UTC" }); }
389
+ catch (error) { sendJson(res, 400, { error: error.message });return; }
386
390
  let analytics = null;
387
391
  if (query.get("analytics") === "1") {
388
392
  try {
389
393
  const timeZone = query.get("time_zone") || "UTC";
390
394
  if (timeZone.length > 100) throw new Error("Invalid time zone");
391
- analytics = createUsageAnalytics({ timeZone, qualifyProviders: !provider });
395
+ analytics = createUsageAnalytics({ timeZone, qualifyProviders: !provider, from: selection.filters.from, to: selection.filters.to });
392
396
  } catch {
393
397
  sendJson(res, 400, { error: "Select a valid usage time zone" });
394
398
  return;
@@ -396,10 +400,19 @@ export async function handleDashboardApi(req, res, pathname, {
396
400
  }
397
401
  const abort = createRequestAbort(req, res);
398
402
  try {
399
- const analysis = analytics && !usageSummaryFn
400
- ? await analyzeUsageLogs(undefined, { timeZone: query.get("time_zone") || "UTC", provider, signal: abort.signal }) : null;
401
- const summary = analysis?.summary || await (usageSummaryFn || (options => summarizeUsageLogs(undefined, { ...options, signal: abort.signal })))({ provider, ...(analytics ? { onRecord: analytics.record } : {}) });
402
- if (!abort.signal.aborted) sendJson(res, 200, { source: "local_usage_log", provider: provider || "all", providers: summary.providers, ...usageTable(summary), ...(analytics ? { analytics: analysis?.analytics || analytics.snapshot() } : {}) });
403
+ const filtered = selection.filters.model || selection.filters.from || selection.filters.to;
404
+ const observedModels = new Set();
405
+ const recordFilter = record => {
406
+ if (observedModels.size < 100) observedModels.add(provider ? record.model || "unknown" : `${usageProvider(record)} / ${record.model || "unknown"}`);
407
+ return selection.matches(record);
408
+ };
409
+ const analysis = (analytics || filtered) && !usageSummaryFn
410
+ ? await analyzeUsageLogs(undefined, { provider, model: selection.filters.model, from: selection.filters.from, to: selection.filters.to, timeZone: selection.filters.time_zone, signal: abort.signal }) : null;
411
+ const summary = analysis?.summary || await (usageSummaryFn || (options => summarizeUsageLogs(undefined, { ...options, signal: abort.signal })))({ provider,
412
+ ...(filtered ? { recordFilter } : {}), ...(analytics ? { onRecord: analytics.record } : {}) });
413
+ const availableModels = analysis?.analytics.models || (observedModels.size ? [...observedModels].sort() : Object.keys(provider ? summary.byModel : summary.bySourceModel || summary.byModel).sort().slice(0, 100));
414
+ if (!abort.signal.aborted) sendJson(res, 200, { source: "local_usage_log", provider: provider || "all", providers: summary.providers, filters: selection.filters, available_models: availableModels,
415
+ ...usageTable(summary), ...(analytics ? { analytics: analysis?.analytics || analytics.snapshot() } : {}) });
403
416
  } catch {
404
417
  if (!abort.signal.aborted) sendJson(res, 500, { error: "Could not read local usage summary" });
405
418
  } finally { abort.cleanup(); }
@@ -1,3 +1,5 @@
1
+ import { antigravityCopilotModels } from "./antigravity-models.mjs";
2
+ import { sourceModels } from "./client-model-plan.mjs";
1
3
  import { isImageModel, imageModelCatalog } from "./image-models.mjs";
2
4
  import os from "node:os";
3
5
  import { publicModelCatalog } from "./provider-metadata.mjs";
@@ -60,6 +62,17 @@ export function selectableCopilotModels(payload) {
60
62
  return { advertised: data.length, models };
61
63
  }
62
64
 
65
+ export function publicCopilotModelCatalog(payload) {
66
+ const data=Array.isArray(payload)?payload:payload.data;
67
+ const codex=new Set(sourceModels({id:"github",registry:{models:{data}}},"codex")
68
+ .filter(model=>model.model_picker_enabled!==false&&(!model.policy?.state||model.policy.state==="enabled")).map(model=>model.id));
69
+ const antigravity=new Set(antigravityCopilotModels(payload).map(model=>model.model));
70
+ return publicModelCatalog(data,{
71
+ selectable:model=>codex.has(model.id)||antigravity.has(model.id)||imageModelCatalog([model]).length>0,
72
+ clients:model=>[...(codex.has(model.id)||isImageModel(model)?["codex"]:[]),...(antigravity.has(model.id)?["antigravity"]:[])],
73
+ });
74
+ }
75
+
63
76
  function validationFailure(validation) {
64
77
  const httpStatus = validation?.status ? ` (HTTP ${validation.status})` : "";
65
78
  return `GitHub Copilot authentication failed: ${validation?.reason || "unknown error"}${httpStatus}`;
@@ -139,10 +152,7 @@ async function lookupLiveModels(credentials, { fetchImpl, timeoutMs, vscodeVersi
139
152
  }
140
153
  const catalog = selectableCopilotModels(payload);
141
154
  if (includeAll) {
142
- const selected = new Set(catalog.models.map(model => model.id));
143
- catalog.models = publicModelCatalog(Array.isArray(payload) ? payload : payload.data, {
144
- selectable: model => selected.has(model.id) || imageModelCatalog([model]).length > 0, clients: model => selected.has(model.id) || isImageModel(model) ? ["codex"] : [],
145
- });
155
+ catalog.models = publicCopilotModelCatalog(payload);
146
156
  }
147
157
  let upstreamHost = "GitHub Copilot";
148
158
  try { upstreamHost = new URL(apiBase).hostname; } catch {}
@@ -4,7 +4,7 @@ import { providerDescriptors } from "./provider-descriptors.mjs";
4
4
  import { autoReviewPreference, writeAutoReviewModel } from "./user-settings.mjs";
5
5
  import { autoReviewReasoningEfforts, DEFAULT_CODEX_AUTO_REVIEW_MODEL, responsesModelIdsFromCopilotModels } from "./models.mjs";
6
6
  import { publicModelCatalog } from "./provider-metadata.mjs";
7
- import { selectableCopilotModels } from "./live-models.mjs";
7
+ import { publicCopilotModelCatalog } from "./live-models.mjs";
8
8
  import { createGithubProvider } from "./providers/github.mjs";
9
9
  import { readProviderSettings, writeProviderSettings } from "./provider-settings.mjs";
10
10
  import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey, readM365Account, m365AccountKey } from "./m365-settings.mjs";
@@ -249,10 +249,9 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, refreshGit
249
249
  if (provider === "github") {
250
250
  if (!refreshGithubCatalog) return null;
251
251
  const catalog = await refreshGithubCatalog();
252
- const selected = new Set(selectableCopilotModels(catalog).models.map(model => model.id));
253
252
  const upstreamHost = githubClient.runtimeStatus?.().upstream_host;
254
253
  return { source: "live", checkedAt: new Date().toISOString(), upstreamHost: upstreamHost && upstreamHost !== "unknown" ? upstreamHost : "GitHub Copilot", advertised: catalog.data.length,
255
- models: publicModelCatalog(catalog.data, { selectable: model => selected.has(model.id) || imageModelCatalog([model]).length > 0, clients: model => selected.has(model.id) || isImageModel(model) ? ["codex"] : [] }) };
254
+ models: publicCopilotModelCatalog(catalog) };
256
255
  }
257
256
  if (provider !== "m365") throw Object.assign(new Error("Unknown provider"), { statusCode: 400 });
258
257
  if (!enabled || !["darwin", "win32"].includes(platform)) throw unavailable(!enabled ? "m365_disabled" : "m365_unsupported");
@@ -4,6 +4,7 @@ import { isProviderId } from "./provider-metadata.mjs";
4
4
  import { applicationLabel } from "./request-application.mjs";
5
5
  import { createContextMetrics } from "./context-metrics.mjs";
6
6
  import { createChangeSignal } from "./activity-events.mjs";
7
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
7
8
 
8
9
  const PERFORMANCE_ROUTES = Object.freeze(["responses", "responses_compact"]);
9
10
  const PREPARATION_STAGES = Object.freeze(["admission", "body", "history", "images", "serialization"]);
@@ -346,8 +347,10 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
346
347
  observeContext(values) {
347
348
  if (finished || !values || typeof values !== "object") return;
348
349
  if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
349
- for (const key of [...Object.keys(context), "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "privacy_pending_bytes", "privacy_new_bytes", "privacy_pending_windows", "privacy_wait_budget_ms", "privacy_error", "privacy_event_type", "privacy_channel_type", "privacy_buffered_bytes", "privacy_terminal_seen", "client_tool_errors_received"]) {
350
+ for (const key of [...Object.keys(context), "requested_model", "usage_state", "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "privacy_pending_bytes", "privacy_new_bytes", "privacy_pending_windows", "privacy_wait_budget_ms", "privacy_error", "privacy_event_type", "privacy_channel_type", "privacy_buffered_bytes", "privacy_terminal_seen", "client_tool_errors_received"]) {
350
351
  const value = values[key];
352
+ if (key === "requested_model") { if (typeof value === "string" && /^[\w][\w./:@+-]{0,159}$/.test(value) && redactDiagnosticText(value) === value) context[key] = value;continue; }
353
+ if (key === "usage_state") { if (["pending", "reported", "partial", "missing", "unavailable"].includes(value)) context[key] = value;continue; }
351
354
  if (key === "privacy_state") { if (["checked", "failed", "cancelled"].includes(value)) context[key] = value;continue; }
352
355
  if (["privacy_error", "privacy_event_type", "privacy_channel_type"].includes(key)) {
353
356
  if (typeof value === "string" && /^[a-z0-9_.]{1,80}$/.test(value)) context[key] = value;continue;
@@ -377,6 +380,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
377
380
  },
378
381
  finish({ failed: finishFailed = false, aborted = false, statusCode = 0, rejectionReason } = {}) {
379
382
  if (finished) return;
383
+ if (context.usage_state === "pending") context.usage_state = "missing";
380
384
  if (!sourceStats) assignProvider("unknown");
381
385
  finished = true;
382
386
  activeTotal--;activeRequests.delete(activeId);
@@ -3,6 +3,14 @@ import { terminalCell } from "./terminal-text.mjs";
3
3
  const integer = value => Number.isSafeInteger(value) && value >= 0;
4
4
  const appIds = { codex_app: "codex", codex_cli: "codex", codex: "codex", claude_app: "claude_app", claude_code: "claude_code", gemini_app: "antigravity" };
5
5
  export const TERMINAL_CLIENT_NAMES = Object.freeze({ codex: "Codex", claude_app: "Claude App", claude_code: "Claude Code", gemini: "Antigravity", antigravity: "Antigravity" });
6
+ export function terminalRequestState(row) {
7
+ if (!row.active) return row.state || "unknown";
8
+ if (row.terminal_outcome) return "Finishing";
9
+ if (row.first_output_ms != null) return "Responding";
10
+ if (row.phase === "admission") return "Queued";
11
+ if (row.upstream_attempts > 1) return "Retrying";
12
+ return row.upstream_attempts ? "Waiting upstream" : "Processing input";
13
+ }
6
14
  const labels = { configured: "Configured", paused: "Paused", disabled: "Disabled", not_configured: "Not configured", not_installed: "Not installed",
7
15
  preserved: "Unchanged", partially_preserved: "Partly unchanged", manual_sync: "Manual sync", default_unavailable: "Default unavailable", configuration_unavailable: "Unreadable", unavailable: "Unavailable" };
8
16
  export function terminalUptime(milliseconds) {
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
3
3
  import { summarizeUsage, summarizeUsageLogs, usageLogPath, usageSummaryVersion, subscribeUsageAppends, usageProvider, mergeUsageSummary } from "./usage-store.mjs";
4
4
  import { createUsageAnalytics } from "./usage-analytics.mjs";
5
5
  import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
6
+ import { createUsageQuery } from "./usage-query.mjs";
6
7
 
7
8
  const MAX_ENTRIES = 2;
8
9
  const MAX_BYTES = 2 * 1024 * 1024;
@@ -56,9 +57,10 @@ function observe() {
56
57
  });
57
58
  }
58
59
 
59
- export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "", signal } = {}) {
60
+ export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "", model = "", days = "all", from = "", to = "", signal } = {}) {
61
+ const selection = createUsageQuery({ provider, model, days, from, to, timeZone, now });
60
62
  const zone = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
61
- const file = path.resolve(filePath), query = `${file}\0${provider}\0${zone.resolvedOptions().timeZone}\0${zone.format(new Date(now))}`;
63
+ const file = path.resolve(filePath), query = `${file}\0${selection.key}\0${zone.format(new Date(now))}`;
62
64
  const version = warn === console.error ? await usageSummaryVersion(file, { settled: false }) : null;
63
65
  const collect = async () => {
64
66
  const cached = version && cache.get(query);
@@ -68,25 +70,34 @@ export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "
68
70
  for (const line of cached.pending) {
69
71
  const record = JSON.parse(line);
70
72
  if (provider && provider !== usageProvider(record)) continue;
73
+ const label = provider ? record.model || "unknown" : `${usageProvider(record)} / ${record.model || "unknown"}`;
74
+ if (cached.models.size < 100) cached.models.add(label);else if (!cached.models.has(label)) cached.modelsTruncated = true;
75
+ if (!selection.matches(record)) continue;
71
76
  const one = summarizeUsage([record]);mergeUsageSummary(cached.summary, one);cached.analytics.record(record, one);
72
77
  }
73
78
  cached.pending = [];cached.pendingBytes = 0;
74
- const result = { summary: cached.summary, analytics: cached.analytics.snapshot() };
79
+ const snapshot = cached.analytics.snapshot();
80
+ const result = { summary: cached.summary, analytics: { ...snapshot, models: [...cached.models].sort(), models_truncated: snapshot.models_truncated || cached.modelsTruncated }, filters: selection.filters };
75
81
  cached.bytes = Buffer.byteLength(JSON.stringify(result));
76
82
  if (result.analytics.undated_records > 0) cache.delete(query);
77
83
  prune();return result;
78
84
  }
79
85
  cache.delete(query);prune();
80
- const analytics = createUsageAnalytics({ timeZone, now, qualifyProviders: !provider });
81
- let warned = false;
82
- const summary = await summarizeUsageLogs(filePath, { provider, onRecord: analytics.record,
86
+ const analytics = createUsageAnalytics({ timeZone, now, qualifyProviders: !provider, from: selection.filters.from, to: selection.filters.to }), models = new Set();
87
+ let warned = false, modelsTruncated = false;
88
+ const summary = await summarizeUsageLogs(filePath, { provider, onRecord: analytics.record, recordFilter: record => {
89
+ const label = provider ? record.model || "unknown" : `${usageProvider(record)} / ${record.model || "unknown"}`;
90
+ if (models.size < 100) models.add(label);else if (!models.has(label)) modelsTruncated = true;
91
+ return selection.matches(record);
92
+ },
83
93
  warn(message) { warned = true;warn(message); } });
84
- const result = { summary, analytics: analytics.snapshot() };
94
+ const snapshot = analytics.snapshot();
95
+ const result = { summary, analytics: { ...snapshot, models: [...models].sort(), models_truncated: snapshot.models_truncated || modelsTruncated }, filters: selection.filters };
85
96
  const complete = version && await completeLines(file);
86
97
  const after = version ? await usageSummaryVersion(file, { settled: false }) : null;
87
98
  const bytes = Buffer.byteLength(JSON.stringify(result));
88
99
  if (version && complete && after === version && !warned && !result.analytics.undated_records && bytes <= MAX_BYTES) {
89
- cache.set(query, { file, version, summary, analytics, bytes, pending: [], pendingBytes: 0 });observe();prune();
100
+ cache.set(query, { file, version, summary, analytics, models, modelsTruncated, bytes, pending: [], pendingBytes: 0 });observe();prune();
90
101
  }
91
102
  return result;
92
103
  };
@@ -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 } = {}) {