codex-copilot-dx 1.3.8 → 1.3.10
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 +3 -2
- package/docs/ARCHITECTURE.md +24 -4
- package/docs/REFERENCE.md +20 -6
- package/package.json +3 -3
- package/src/adapter.mjs +2 -0
- package/src/claude-gateway.mjs +22 -18
- package/src/cli-command-spec.mjs +3 -0
- package/src/cli-management.mjs +14 -1
- package/src/connection-runtime.mjs +1 -0
- package/src/dashboard/connections.js +1 -1
- package/src/dashboard/features.js +9 -4
- package/src/dashboard/index.html +5 -6
- package/src/dashboard/language.js +7 -2
- package/src/dashboard/privacy.js +6 -4
- package/src/dashboard/usage.js +2 -2
- package/src/dashboard-api.mjs +5 -0
- package/src/http-transport.mjs +1 -0
- package/src/local-privacy.mjs +63 -23
- package/src/messages-history-transfer.mjs +12 -2
- package/src/messages-system-policy.mjs +20 -0
- package/src/model-capabilities.mjs +2 -2
- package/src/privacy-model.mjs +61 -25
- package/src/privacy-transform.mjs +80 -13
- package/src/providers/m365.mjs +5 -2
- package/src/service-control.mjs +7 -1
- package/src/stream-performance.mjs +2 -1
- package/src/terminal-console.mjs +2 -2
- package/src/terminal-state.mjs +2 -1
- package/src/usage-analytics.mjs +10 -4
- package/src/usage-store.mjs +43 -18
- package/src/usage.mjs +18 -5
package/src/providers/m365.mjs
CHANGED
|
@@ -126,7 +126,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
126
126
|
const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
|
|
127
127
|
if (serialized !== undefined) requestHeaders["Content-Length"] = String(Buffer.byteLength(serialized));
|
|
128
128
|
options.onUpstreamStart?.();
|
|
129
|
-
if (body) { markUpstreamStarted(body.stream === true);if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: endpoint.includes("messages") ? body.max_tokens : body.max_output_tokens }); }
|
|
129
|
+
if (body) { if (options.observeUpstream !== false) markUpstreamStarted(body.stream === true);if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: endpoint.includes("messages") ? body.max_tokens : body.max_output_tokens }); }
|
|
130
130
|
try {
|
|
131
131
|
const send = fetchImpl || await transport(options.signal);
|
|
132
132
|
const response = await send(`${M365_API_BASE}${endpoint}`, { method: body ? "POST" : "GET", headers: requestHeaders,
|
|
@@ -233,12 +233,15 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
233
233
|
const adjusted = limitM365CacheTtl(body);
|
|
234
234
|
if (adjusted.changed && !cacheTtlAdjustments) log("info", "Microsoft 365 supports 5m prompt caching; 1h cache retention is capped to 5m. Content and breakpoints are unchanged.");
|
|
235
235
|
cacheTtlAdjustments += adjusted.changed;
|
|
236
|
-
|
|
236
|
+
const requestBody = model.id === adjusted.body.model ? adjusted.body : { ...adjusted.body, model: model.id };
|
|
237
|
+
return request(options.countTokens ? "/v1/messages/count_tokens" : "/v1/messages", requestBody, requestBody === body ? options : { ...options, bodyText: undefined });
|
|
237
238
|
},
|
|
238
239
|
runtimeStatus: () => ({ ...auth.snapshot(), account_bound: Boolean(account), upstream_host: new URL(M365_API_BASE).hostname,
|
|
239
240
|
model_endpoint_cache_entries: catalog?.data.length || 0, model_list_flights: flight ? 1 : 0 }),
|
|
240
241
|
};
|
|
241
242
|
return {
|
|
243
|
+
messagesSystemMode: "native",
|
|
244
|
+
coordinateMessagesCounts: true,
|
|
242
245
|
id: "m365", client, registry, auth, refresh, profileId: profile,
|
|
243
246
|
models: family => m365Models(catalog, family),
|
|
244
247
|
catalog: () => catalog?.data || [],
|
package/src/service-control.mjs
CHANGED
|
@@ -23,11 +23,13 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
23
23
|
try { imageConfigured = Boolean(readImages()); } catch {}
|
|
24
24
|
try { predictionConfigured = readPrediction().enabled === true; } catch {}
|
|
25
25
|
const enabled = nightlyUpdatePreference(options), nightly = nightlyStatus();
|
|
26
|
-
|
|
26
|
+
const localPrivacy = providerRuntime?.privacy?.snapshot();
|
|
27
|
+
return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: localPrivacy,
|
|
27
28
|
features: { prediction: { ...featureSnapshot(predictionControlSnapshot), bridge: prediction?.bridge || "stopped", active: prediction?.active === true }, image: featureSnapshot(imageSetupSummary) },
|
|
28
29
|
decoded_body: decodedBodyLimitPreference(options), manual_update: { available: typeof manualUpdate === "function" }, last_operation: lastOperation,
|
|
29
30
|
nightly_update: { enabled, ...nightly, effect: enabled && !nightly ? "next_start" : "immediate" },
|
|
30
31
|
effective: {
|
|
32
|
+
privacy_enabled: { value: localPrivacy?.effective_enabled === true, state: !localPrivacy ? "unavailable" : !localPrivacy.enabled ? "off" : localPrivacy.state === "ready" ? "ready" : "not_ready" },
|
|
31
33
|
terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
|
|
32
34
|
state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
|
|
33
35
|
open_webui: { value: saved.open_webui, state: "next_start" },
|
|
@@ -61,6 +63,10 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
61
63
|
if (decodedBodyLimitPreference(options).source === "environment") throw new Error("Request limit is controlled by the launch environment");
|
|
62
64
|
writeDecodedBodyLimitMib(input.mib, options);
|
|
63
65
|
} else if (["preferences", "reset_preferences", "restore_preferences"].includes(input.action)) {
|
|
66
|
+
if (input.action === "preferences" && Object.hasOwn(input.values || {}, "privacy_enabled")
|
|
67
|
+
&& input.values.privacy_enabled !== settingsPreferencesSnapshot(options).values.privacy_enabled) {
|
|
68
|
+
throw Object.assign(new Error("Use local masking controls to prepare or disable protection"), { code: "ccdx_settings_privacy_action_required", statusCode: 400 });
|
|
69
|
+
}
|
|
64
70
|
const before = nightlyUpdatePreference(options);
|
|
65
71
|
writeSettingsPreferences(input, options);
|
|
66
72
|
if (input.action !== "preferences" || Object.keys(input.values || {}).some(key => key.startsWith("privacy_"))) providerRuntime?.privacy?.settingsChanged();
|
|
@@ -342,8 +342,9 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
342
342
|
observeContext(values) {
|
|
343
343
|
if (finished || !values || typeof values !== "object") return;
|
|
344
344
|
if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
|
|
345
|
-
for (const key of [...Object.keys(context), "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "client_tool_errors_received"]) {
|
|
345
|
+
for (const key of [...Object.keys(context), "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "client_tool_errors_received"]) {
|
|
346
346
|
const value = values[key];
|
|
347
|
+
if (key === "privacy_state") { if (["checked", "failed", "cancelled"].includes(value)) context[key] = value;continue; }
|
|
347
348
|
if (["capability_revision", "capability_constraints"].includes(key)) {
|
|
348
349
|
if (typeof value === "string" && /^[a-z0-9_,]{1,80}$/.test(value)) context[key] = value;continue;
|
|
349
350
|
}
|
package/src/terminal-console.mjs
CHANGED
|
@@ -55,13 +55,13 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
|
|
|
55
55
|
const rate = usage.cache_hit_rate;
|
|
56
56
|
const cacheHit = Number.isFinite(rate) && rate >= 0 && rate <= 1 ? `${usage.cache_hit_rate_partial ? "~" : ""}${(rate * 100).toFixed(1)}%` : "—";
|
|
57
57
|
const usageRows = [[left < 23 ? "Records" : "Usage records", usage.records ?? null], ["Input", usage.input_tokens ?? null], [left < 23 ? "Reused" : "Reused input", usage.cached_input_tokens ?? null],
|
|
58
|
-
["Output", usage.output_tokens ?? null], [left < 23 ? "Partial" : "Partial records", usage.partial_records ?? null], ["Cache hit", cacheHit]];
|
|
58
|
+
[left < 23 ? "Written" : "Cache write", usage.cache_write_input_tokens ?? null], ["Output", usage.output_tokens ?? null], [left < 23 ? "Partial" : "Partial records", usage.partial_records ?? null], ["Cache hit", cacheHit]];
|
|
59
59
|
const requestRows = [["Total", requests], ["Active", inferenceActive], ["Completed", sum("completed")], ["Incomplete", sum("incomplete")], ["Failed", sum("failed")], ["Cancelled", sum("cancelled")]];
|
|
60
60
|
if (sum("unknown")) { usageRows.push(["", ""]);requestRows.push(["Unknown", sum("unknown")]); }
|
|
61
61
|
const title = compactTitle ? [`┌─ Usage ${"─".repeat(left - 8)}┬─ Requests ${"─".repeat(right - 11)}┐`]
|
|
62
62
|
: [rule("┌", "┬", "┐"), row(cell("Usage / this run", undefined, left), cell(right < 23 ? "Requests" : "Model requests", undefined, right)), rule("├", "┼", "┤")];
|
|
63
63
|
return [...title,
|
|
64
|
-
...usageRows.map(([label, value], index) => row(cell(label, value === undefined ? (label ? null : undefined) : value, left), cell(...requestRows[index], right))), rule("└", "┴", "┘")];
|
|
64
|
+
...usageRows.map(([label, value], index) => row(cell(label, value === undefined ? (label ? null : undefined) : value, left), cell(...(requestRows[index] || ["", undefined]), right))), rule("└", "┴", "┘")];
|
|
65
65
|
}
|
|
66
66
|
function render() {
|
|
67
67
|
if (!running || !supported() || verbose) { frameDelay = 1000;return; }
|
package/src/terminal-state.mjs
CHANGED
|
@@ -46,7 +46,8 @@ export function projectTerminalState(data = {}) {
|
|
|
46
46
|
if (lastFailure) {
|
|
47
47
|
const app = TERMINAL_CLIENT_NAMES[appIds[lastFailure.application]] || "Unidentified client";
|
|
48
48
|
const source = connection?.providers?.find(item => item.id === lastFailure.provider)?.name || ({ github: "GitHub Copilot", m365: "Microsoft 365" }[lastFailure.provider]) || lastFailure.provider || "Unknown source";
|
|
49
|
-
const causes = { m365_network_error: "Network request failed", m365_catalog_http_403: "Model catalog access denied", ccdx_api_model_unavailable: "Selected model is unavailable", ccdx_client_source_disabled: "Model access is paused"
|
|
49
|
+
const causes = { m365_network_error: "Network request failed", m365_catalog_http_403: "Model catalog access denied", ccdx_api_model_unavailable: "Selected model is unavailable", ccdx_client_source_disabled: "Model access is paused",
|
|
50
|
+
ccdx_privacy_busy: "Local masking is busy; nothing was sent", ccdx_privacy_check_timeout: "Local masking check timed out; nothing was sent", ccdx_privacy_engine_invalid: "Local masking result was invalid; nothing was sent" };
|
|
50
51
|
const message = causes[lastFailure.code] || (lastFailure.route === "messages_count_tokens" ? "Token-count check failed" : lastFailure.http_status === 401 ? "Sign-in was rejected" : lastFailure.http_status === 403 ? "Access was denied" : lastFailure.http_status === 429 ? "Request limit reached" : "Request failed");
|
|
51
52
|
issue = { label: `${terminalCell(app)} / ${terminalCell(source)}: ${message}`, request_id: lastFailure.request_id, application: lastFailure.application };
|
|
52
53
|
}
|
package/src/usage-analytics.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { cacheReadTokens, usageCacheHitRate, usageProvider } from "./usage-store
|
|
|
3
3
|
const DAY_MS = 86400000;
|
|
4
4
|
const DAYS = 365;
|
|
5
5
|
const MAX_MODELS = 100;
|
|
6
|
-
const TOKEN_FIELDS = ["input_tokens", "output_tokens", "total_tokens", "cached_input_tokens", "cache_read_input_tokens", "cache_hit_unknown_requests", "cache_hit_invalid_requests"];
|
|
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
8
|
export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), qualifyProviders = false } = {}) {
|
|
9
9
|
const formatter = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
|
|
@@ -29,11 +29,17 @@ export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), quali
|
|
|
29
29
|
function row(values = {}) {
|
|
30
30
|
return {
|
|
31
31
|
requests: values.requests || 0,
|
|
32
|
-
input_tokens: values.input_tokens
|
|
33
|
-
output_tokens: values.output_tokens
|
|
34
|
-
total_tokens: values.total_tokens ?? (values.
|
|
32
|
+
input_tokens: values.input_tokens ?? (values.requests ? null : 0),
|
|
33
|
+
output_tokens: values.output_tokens ?? (values.requests ? null : 0),
|
|
34
|
+
total_tokens: values.total_tokens ?? (!values.tokens_partial && Number.isFinite(values.input_tokens) && Number.isFinite(values.output_tokens)
|
|
35
|
+
? values.input_tokens + values.output_tokens : values.requests ? null : 0),
|
|
35
36
|
cache_read_tokens: cacheReadTokens(values) ?? null,
|
|
37
|
+
cache_write_input_tokens: values.cache_write_input_tokens ?? null,
|
|
36
38
|
cache_hit_rate: usageCacheHitRate(values),
|
|
39
|
+
cache_hit_known_requests: values.cache_hit_known_requests || 0,
|
|
40
|
+
cache_hit_unknown_requests: values.cache_hit_unknown_requests || 0,
|
|
41
|
+
cache_hit_input_tokens: values.cache_hit_input_tokens ?? null,
|
|
42
|
+
cache_hit_read_tokens: values.cache_hit_read_tokens ?? null,
|
|
37
43
|
cache_hit_rate_partial: values.cache_hit_unknown_requests > 0,
|
|
38
44
|
tokens_partial: values.tokens_partial === true || values.cache_hit_invalid_requests > 0,
|
|
39
45
|
};
|
package/src/usage-store.mjs
CHANGED
|
@@ -71,18 +71,19 @@ function hasPositiveTokenValue(usage) {
|
|
|
71
71
|
|
|
72
72
|
function normalizeResponsesUsage(usage) {
|
|
73
73
|
if (!usage || typeof usage !== "object") return undefined;
|
|
74
|
+
const count = value => Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
74
75
|
const cachedInput = numberOrUndefined(usage.cached_input_tokens ?? usage.input_tokens_details?.cached_tokens);
|
|
75
76
|
const out = compactObject({
|
|
76
|
-
input_tokens:
|
|
77
|
+
input_tokens: count(usage.input_tokens),
|
|
77
78
|
cached_input_tokens: cachedInput >= 0 ? cachedInput : undefined,
|
|
78
|
-
output_tokens:
|
|
79
|
-
reasoning_output_tokens:
|
|
80
|
-
total_tokens:
|
|
79
|
+
output_tokens: count(usage.output_tokens),
|
|
80
|
+
reasoning_output_tokens: count(usage.reasoning_output_tokens ?? usage.output_tokens_details?.reasoning_tokens),
|
|
81
|
+
total_tokens: count(usage.total_tokens),
|
|
81
82
|
});
|
|
82
|
-
if (out.total_tokens === undefined &&
|
|
83
|
-
out.total_tokens =
|
|
83
|
+
if (out.total_tokens === undefined && out.input_tokens !== undefined && out.output_tokens !== undefined) {
|
|
84
|
+
out.total_tokens = out.input_tokens + out.output_tokens;
|
|
84
85
|
}
|
|
85
|
-
return
|
|
86
|
+
return Object.keys(out).length ? out : undefined;
|
|
86
87
|
}
|
|
87
88
|
|
|
88
89
|
function normalizeCopilotUsage(copilotUsage) {
|
|
@@ -203,17 +204,16 @@ function scheduleUsageWriteDrain() {
|
|
|
203
204
|
export function recordUsage(record) {
|
|
204
205
|
if (!record) return Promise.resolve();
|
|
205
206
|
const usage = record.usage || {};
|
|
206
|
-
const { cached
|
|
207
|
+
const { cached } = usageCacheEvidence(usage);
|
|
207
208
|
const provider = usageProvider(record), label = runtimeUsageByProvider.has(provider) || runtimeUsageByProvider.size < 18 ? provider : "other";
|
|
208
209
|
if (!runtimeUsageByProvider.has(label)) runtimeUsageByProvider.set(label, { records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 });
|
|
209
210
|
for (const totals of [runtimeUsage, runtimeUsageByProvider.get(label)]) {
|
|
210
211
|
totals.records++;
|
|
211
|
-
for (const [target, value] of [["input_tokens", usage.input_tokens], ["cached_input_tokens", cached], ["output_tokens", usage.output_tokens]]) {
|
|
212
|
-
if (Number.isFinite(value) && value >= 0) totals[target]
|
|
212
|
+
for (const [target, value] of [["input_tokens", usage.input_tokens], ["cached_input_tokens", cached], ["cache_write_input_tokens", usage.cache_write_input_tokens], ["output_tokens", usage.output_tokens]]) {
|
|
213
|
+
if (Number.isFinite(value) && value >= 0) totals[target] = (totals[target] || 0) + value;
|
|
213
214
|
}
|
|
214
215
|
if (!Number.isFinite(usage.input_tokens) || !Number.isFinite(usage.output_tokens) || cached === undefined) totals.partial_records++;
|
|
215
|
-
|
|
216
|
-
if (invalid) totals.cache_hit_invalid_requests = (totals.cache_hit_invalid_requests || 0) + 1;
|
|
216
|
+
addCacheEvidence(totals, usage);
|
|
217
217
|
}
|
|
218
218
|
if (process.env.CCDX_DISABLE_USAGE === "1") return Promise.resolve();
|
|
219
219
|
const filePath = usageLogPath();
|
|
@@ -331,7 +331,12 @@ export function summarizeUsage(records, { provider = "" } = {}) {
|
|
|
331
331
|
if (provider && provider !== source) continue;
|
|
332
332
|
summary.providers[source] = (summary.providers[source] || 0) + 1;
|
|
333
333
|
summary.requests += 1;
|
|
334
|
-
|
|
334
|
+
let observed = record.usage;
|
|
335
|
+
if (observed?.cached_input_tokens != null && observed?.cache_read_input_tokens != null) {
|
|
336
|
+
observed = { ...observed };delete observed.cache_read_input_tokens;
|
|
337
|
+
if (cacheReadTokens(record.usage) === undefined) delete observed.cached_input_tokens;
|
|
338
|
+
}
|
|
339
|
+
addUsageTotals(summary.totals, observed);
|
|
335
340
|
if (record.copilot_usage) {
|
|
336
341
|
summary.totals.copilot_total_tokens = (summary.totals.copilot_total_tokens || 0) + (record.copilot_usage.total_tokens || 0);
|
|
337
342
|
summary.totals.total_nano_aiu = (summary.totals.total_nano_aiu || 0) + (record.copilot_usage.total_nano_aiu || 0);
|
|
@@ -340,16 +345,14 @@ export function summarizeUsage(records, { provider = "" } = {}) {
|
|
|
340
345
|
if (!Object.hasOwn(summary.byModel, model)) Object.defineProperty(summary.byModel, model, { value: { requests: 0 }, enumerable: true, configurable: true, writable: true });
|
|
341
346
|
const modelTotals = summary.byModel[model];
|
|
342
347
|
modelTotals.requests += 1;
|
|
343
|
-
addUsageTotals(modelTotals,
|
|
344
|
-
const { unknown, invalid } = usageCacheEvidence(record.usage || {});
|
|
348
|
+
addUsageTotals(modelTotals, observed);
|
|
345
349
|
const qualified = `${source} / ${model}`;
|
|
346
350
|
if (!Object.hasOwn(summary.bySourceModel, qualified)) summary.bySourceModel[qualified] = { requests: 0 };
|
|
347
351
|
const sourceTotals = summary.bySourceModel[qualified];
|
|
348
352
|
sourceTotals.requests++;
|
|
349
|
-
addUsageTotals(sourceTotals,
|
|
353
|
+
addUsageTotals(sourceTotals, observed);
|
|
350
354
|
for (const target of [summary.totals, modelTotals, sourceTotals]) {
|
|
351
|
-
|
|
352
|
-
if (invalid) target.cache_hit_invalid_requests = (target.cache_hit_invalid_requests || 0) + 1;
|
|
355
|
+
addCacheEvidence(target, record.usage || {});
|
|
353
356
|
}
|
|
354
357
|
}
|
|
355
358
|
return summary;
|
|
@@ -429,6 +432,11 @@ export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = con
|
|
|
429
432
|
}
|
|
430
433
|
|
|
431
434
|
export function cacheReadTokens(usage = {}) {
|
|
435
|
+
if (usage.cached_input_tokens != null && usage.cache_read_input_tokens != null
|
|
436
|
+
&& usage.cache_hit_known_requests === undefined && usage.cache_hit_unknown_requests === undefined) {
|
|
437
|
+
return Number.isFinite(usage.cached_input_tokens) && usage.cached_input_tokens >= 0
|
|
438
|
+
&& usage.cached_input_tokens === usage.cache_read_input_tokens ? usage.cached_input_tokens : undefined;
|
|
439
|
+
}
|
|
432
440
|
const values = [usage.cache_read_input_tokens, usage.cached_input_tokens]
|
|
433
441
|
.filter((value) => Number.isFinite(value));
|
|
434
442
|
const value = values.length > 0 ? values.reduce((total, current) => total + current, 0) : undefined;
|
|
@@ -436,6 +444,11 @@ export function cacheReadTokens(usage = {}) {
|
|
|
436
444
|
}
|
|
437
445
|
|
|
438
446
|
export function usageCacheHitRate(usage = {}) {
|
|
447
|
+
if (usage.cache_hit_known_requests !== undefined || usage.cache_hit_unknown_requests !== undefined) {
|
|
448
|
+
const input = usage.cache_hit_input_tokens, cached = usage.cache_hit_read_tokens;
|
|
449
|
+
return usage.cache_hit_known_requests > 0 && Number.isFinite(input) && input > 0
|
|
450
|
+
&& Number.isFinite(cached) && cached >= 0 && cached <= input ? cached / input : null;
|
|
451
|
+
}
|
|
439
452
|
const input = usage.input_tokens;
|
|
440
453
|
const cached = cacheReadTokens(usage);
|
|
441
454
|
if (usage.cache_hit_invalid_requests > 0 || !Number.isFinite(input) || input <= 0
|
|
@@ -443,10 +456,22 @@ export function usageCacheHitRate(usage = {}) {
|
|
|
443
456
|
return cached / input;
|
|
444
457
|
}
|
|
445
458
|
|
|
459
|
+
function addCacheEvidence(target, usage) {
|
|
460
|
+
const { cached, unknown, invalid } = usageCacheEvidence(usage);
|
|
461
|
+
if (unknown) target.cache_hit_unknown_requests = (target.cache_hit_unknown_requests || 0) + 1;
|
|
462
|
+
else {
|
|
463
|
+
target.cache_hit_known_requests = (target.cache_hit_known_requests || 0) + 1;
|
|
464
|
+
target.cache_hit_input_tokens = (target.cache_hit_input_tokens || 0) + usage.input_tokens;
|
|
465
|
+
target.cache_hit_read_tokens = (target.cache_hit_read_tokens || 0) + cached;
|
|
466
|
+
}
|
|
467
|
+
if (invalid) target.cache_hit_invalid_requests = (target.cache_hit_invalid_requests || 0) + 1;
|
|
468
|
+
}
|
|
469
|
+
|
|
446
470
|
function usageCacheEvidence(usage) {
|
|
447
471
|
const input = usage.input_tokens, cached = cacheReadTokens(usage);
|
|
448
472
|
const unknown = !Number.isFinite(input) || input < 0 || !Number.isFinite(cached) || cached < 0 || cached > input;
|
|
449
473
|
const invalid = (input != null && (!Number.isFinite(input) || input < 0))
|
|
474
|
+
|| (usage.cached_input_tokens != null && usage.cache_read_input_tokens != null && cached === undefined)
|
|
450
475
|
|| [usage.cached_input_tokens, usage.cache_read_input_tokens].some(value => value != null && (!Number.isFinite(value) || value < 0))
|
|
451
476
|
|| (Number.isFinite(input) && Number.isFinite(cached) && cached > input);
|
|
452
477
|
return { cached, unknown, invalid };
|
package/src/usage.mjs
CHANGED
|
@@ -28,6 +28,8 @@ function fmt(n) {
|
|
|
28
28
|
return Number.isFinite(n) ? n.toLocaleString("en-US") : "0";
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
const tokenCount = n => Number.isFinite(n) ? fmt(n) : "—";
|
|
32
|
+
|
|
31
33
|
function tableNumber(n) {
|
|
32
34
|
return Number.isFinite(n) ? n.toLocaleString("en-US") : undefined;
|
|
33
35
|
}
|
|
@@ -53,13 +55,13 @@ function formatPlainUsageSummary(summary, filePath, { sanitize = false } = {}) {
|
|
|
53
55
|
}
|
|
54
56
|
lines.push(
|
|
55
57
|
`Records: ${fmt(summary.requests)}`,
|
|
56
|
-
`Tokens: input=${
|
|
57
|
-
`Cache hit: ${cacheHitPercent(summary.totals)} (cached/input tokens)`,
|
|
58
|
+
`Tokens: input=${tokenCount(summary.totals.input_tokens)} cache_read=${tokenCount(cacheReadTokens(summary.totals))} cache_write=${tokenCount(summary.totals.cache_write_input_tokens)} output=${tokenCount(summary.totals.output_tokens)} total=${tokenCount(summary.totals.total_tokens)}`,
|
|
59
|
+
`Cache hit: ${cacheHitPercent(summary.totals)} (cached/input tokens; valid paired records only)`,
|
|
58
60
|
"",
|
|
59
61
|
"By model:",
|
|
60
62
|
);
|
|
61
63
|
for (const [model, row] of Object.entries(usageModelGroups(summary))) {
|
|
62
|
-
lines.push(` ${terminalCell(model)}: records=${fmt(row.requests)} input=${
|
|
64
|
+
lines.push(` ${terminalCell(model)}: records=${fmt(row.requests)} input=${tokenCount(row.input_tokens)} cache_read=${tokenCount(cacheReadTokens(row))} cache_write=${tokenCount(row.cache_write_input_tokens)} output=${tokenCount(row.output_tokens)} total=${tokenCount(row.total_tokens)} cache_hit=${cacheHitPercent(row)}`);
|
|
63
65
|
}
|
|
64
66
|
return (sanitize ? lines.map((line) => terminalCell(line, { fallback: "" })) : lines).join("\n");
|
|
65
67
|
}
|
|
@@ -77,6 +79,7 @@ function usageTableRow(model, usage) {
|
|
|
77
79
|
records: tableNumber(usage.requests),
|
|
78
80
|
input: tableNumber(usage.input_tokens),
|
|
79
81
|
cacheRead: tableNumber(cacheReadTokens(usage)),
|
|
82
|
+
cacheWrite: tableNumber(usage.cache_write_input_tokens),
|
|
80
83
|
output: tableNumber(usage.output_tokens),
|
|
81
84
|
total: tableNumber(usage.total_tokens),
|
|
82
85
|
cacheHit: cacheHitPercent(usage),
|
|
@@ -84,7 +87,7 @@ function usageTableRow(model, usage) {
|
|
|
84
87
|
}
|
|
85
88
|
|
|
86
89
|
function usageDetailLine(model, usage) {
|
|
87
|
-
return `${terminalCell(model)}: input=${
|
|
90
|
+
return `${terminalCell(model)}: input=${tokenCount(usage.input_tokens)} cache_read=${tokenCount(cacheReadTokens(usage))} cache_write=${tokenCount(usage.cache_write_input_tokens)} output=${tokenCount(usage.output_tokens)} cache_hit=${cacheHitPercent(usage)}`;
|
|
88
91
|
}
|
|
89
92
|
|
|
90
93
|
function formatTableUsageSummary(summary, filePath, output) {
|
|
@@ -95,10 +98,11 @@ function formatTableUsageSummary(summary, filePath, output) {
|
|
|
95
98
|
{ key: "records", label: "RECORDS", align: "right" },
|
|
96
99
|
{ key: "input", label: "INPUT", align: "right" },
|
|
97
100
|
{ key: "cacheRead", label: "CACHE READ", align: "right" },
|
|
101
|
+
{ key: "cacheWrite", label: "CACHE WRITE", align: "right" },
|
|
98
102
|
{ key: "output", label: "OUTPUT", align: "right" },
|
|
99
103
|
{ key: "total", label: "TOTAL", align: "right" },
|
|
100
104
|
];
|
|
101
|
-
const compactColumns = [columns[0], columns[1], columns[
|
|
105
|
+
const compactColumns = [columns[0], columns[1], columns[6]];
|
|
102
106
|
const modelUsage = Object.entries(usageModelGroups(summary))
|
|
103
107
|
.map(([model, row]) => ({ model, row }))
|
|
104
108
|
.sort(compareModelUsage);
|
|
@@ -111,6 +115,11 @@ function formatTableUsageSummary(summary, filePath, output) {
|
|
|
111
115
|
width: cliOutputWidth(output),
|
|
112
116
|
gap: 1,
|
|
113
117
|
});
|
|
118
|
+
const writeOmitted = table.compact || table.overflow;
|
|
119
|
+
if (writeOmitted) {
|
|
120
|
+
columns.splice(columns.findIndex(column => column.key === "cacheWrite"), 1);
|
|
121
|
+
table = formatResponsiveCliTable({ columns: [...columns, { key: "cacheHit", label: "HIT %", align: "right" }], compactColumns: columns, rows, width: cliOutputWidth(output), gap: 1 });
|
|
122
|
+
}
|
|
114
123
|
const rateFits = !table.compact;
|
|
115
124
|
if (table.overflow) {
|
|
116
125
|
table = formatResponsiveCliTable({ columns, compactColumns, rows, width: cliOutputWidth(output), gap: 1 });
|
|
@@ -118,6 +127,10 @@ function formatTableUsageSummary(summary, filePath, output) {
|
|
|
118
127
|
table.compact = false;
|
|
119
128
|
}
|
|
120
129
|
const lines = [`Usage log: ${safePath}`, ...providerSummaryLines(summary), "", table.output];
|
|
130
|
+
if (writeOmitted && !table.compact && Number.isFinite(totalUsage.cache_write_input_tokens)) {
|
|
131
|
+
lines.push("", "Cache writes:", `TOTAL: ${tokenCount(totalUsage.cache_write_input_tokens)}`,
|
|
132
|
+
...modelUsage.filter(({ row }) => Number.isFinite(row.cache_write_input_tokens)).map(({ model, row }) => `${terminalCell(model)}: ${tokenCount(row.cache_write_input_tokens)}`));
|
|
133
|
+
}
|
|
121
134
|
if (table.compact) {
|
|
122
135
|
lines.push(
|
|
123
136
|
"",
|