codex-copilot-dx 0.10.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/bin/cli.mjs +1 -0
- package/docs/ARCHITECTURE.md +27 -9
- package/docs/README.md +2 -0
- package/docs/REFERENCE.md +79 -10
- package/package.json +2 -2
- package/src/adapter.mjs +2 -1
- package/src/claude-client-config.mjs +15 -3
- package/src/claude-gateway.mjs +12 -6
- package/src/claude-models.mjs +26 -0
- package/src/cli-options.mjs +4 -3
- package/src/dashboard/index.html +40 -37
- package/src/dashboard/language.js +38 -0
- package/src/dashboard/refresh.js +2 -1
- package/src/dashboard/status.js +35 -26
- package/src/dashboard/ui.css +6 -0
- package/src/dashboard/ui.js +109 -21
- package/src/dashboard-api.mjs +48 -7
- package/src/live-models.mjs +11 -3
- package/src/optional-routes.mjs +1 -1
- package/src/provider-metadata.mjs +21 -0
- package/src/provider-runtime.mjs +67 -19
- package/src/providers/m365-auth.mjs +4 -4
- package/src/providers/m365.mjs +10 -2
- package/src/usage-analysis.mjs +1 -1
- package/src/usage-analytics.mjs +3 -3
- package/src/usage-store.mjs +29 -16
- package/src/usage.mjs +13 -7
package/src/provider-runtime.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
|
+
import { publicModelCatalog } from "./provider-metadata.mjs";
|
|
2
3
|
import { createGithubProvider } from "./providers/github.mjs";
|
|
3
4
|
import { readProviderSettings, writeProviderSettings } from "./provider-settings.mjs";
|
|
4
|
-
import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey } from "./m365-settings.mjs";
|
|
5
|
+
import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey, M365_GATEWAY_PORT } from "./m365-settings.mjs";
|
|
5
6
|
|
|
6
7
|
const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavailable (${reason}); GitHub routing was not substituted`),
|
|
7
8
|
{ code: reason, statusCode: 503 });
|
|
@@ -9,17 +10,42 @@ const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavaila
|
|
|
9
10
|
// Composition owns source selection. Providers never modify Codex, prediction,
|
|
10
11
|
// image configuration or each other's credentials.
|
|
11
12
|
export function createProviderRuntime({ githubClient, githubRegistry, githubCredentialFingerprint = "", home, env = process.env, platform = process.platform,
|
|
12
|
-
log = () => {}, createM365, startGateway, configureClients, restoreClients } = {}) {
|
|
13
|
+
corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients } = {}) {
|
|
13
14
|
const options = { home, env, platform }, github = { ...createGithubProvider({ client: githubClient,
|
|
14
15
|
profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
|
|
15
16
|
return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
|
|
16
17
|
let selection = readProviderSettings(options), m365 = null, gateway = null, pending = null, closed = false, serial = null;
|
|
17
18
|
let reason = null, claudeReason = null, clients = { code: "not_configured", app: "not_configured" }, lastClients = {};
|
|
19
|
+
const dashboardProfiles = new Map();
|
|
20
|
+
const dashboardGeneration = provider => {
|
|
21
|
+
const profile = provider.profileId(), previous = dashboardProfiles.get(provider.id);
|
|
22
|
+
if (!previous || previous.profile !== profile) dashboardProfiles.set(provider.id, { profile, generation: (previous?.generation || 0) + 1 });
|
|
23
|
+
return dashboardProfiles.get(provider.id).generation;
|
|
24
|
+
};
|
|
18
25
|
const sessions = new Map();let priorNamespace = null, requestOrder = 0, activeM365Requests = 0;
|
|
19
26
|
let enabled;
|
|
20
27
|
try { enabled = readM365Settings(options).enabled && env.CCDX_M365 !== "0"; }
|
|
21
28
|
catch { enabled = false;reason = "m365_config_invalid"; }
|
|
22
29
|
|
|
30
|
+
let clientSync = null;
|
|
31
|
+
async function syncClaudeClients() {
|
|
32
|
+
if (clientSync) return clientSync;
|
|
33
|
+
clientSync = (async () => {
|
|
34
|
+
const source = m365, profile = source?.profileId();
|
|
35
|
+
if (!source || !gateway || closed || !enabled) return;
|
|
36
|
+
try {
|
|
37
|
+
const integration = configureClients ? null : await import("./claude-client-config.mjs");
|
|
38
|
+
const configure = configureClients || integration.configureClaudeClients;
|
|
39
|
+
const desktopManaged = integration ? await integration.inspectClaudeDesktopPolicy(options) : false;
|
|
40
|
+
if (closed || !enabled || source !== m365 || source.profileId() !== profile || !gateway) return;
|
|
41
|
+
claudeReason = source.models("claude").length ? null : "m365_no_claude_models";
|
|
42
|
+
clients = configure({ ...options, desktopManaged, baseUrl: `http://127.0.0.1:${gateway.port}`,
|
|
43
|
+
apiKey: ensureM365GatewayKey(options), models: source.models("claude") });
|
|
44
|
+
} catch { clients = { code: "configuration_unavailable", app: "configuration_unavailable" };claudeReason = "m365_claude_config_unavailable"; }
|
|
45
|
+
})().finally(() => { clientSync = null; });
|
|
46
|
+
return clientSync;
|
|
47
|
+
}
|
|
48
|
+
|
|
23
49
|
async function startM365(forceRefresh = false) {
|
|
24
50
|
if (closed || !enabled || !["darwin", "win32"].includes(platform)) return null;
|
|
25
51
|
if (pending) return pending;
|
|
@@ -28,12 +54,16 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
28
54
|
if (!m365) {
|
|
29
55
|
const factory = createM365 || (await import("./providers/m365.mjs")).createM365Provider;
|
|
30
56
|
if (closed || !enabled) return null;
|
|
31
|
-
m365 = factory({ home, env, log
|
|
57
|
+
m365 = factory({ home, env, log, onCatalog() {
|
|
58
|
+
// Reconcile after refresh, outside inference serialization and without a watcher.
|
|
59
|
+
setImmediate(() => { if (!pending && gateway && !closed && enabled) void syncClaudeClients(); });
|
|
60
|
+
} });
|
|
32
61
|
}
|
|
33
62
|
await m365.refresh();if (closed || !enabled) return null;
|
|
34
63
|
const claudeModels = m365.models("claude");
|
|
35
|
-
claudeReason = claudeModels.length ?
|
|
36
|
-
if (
|
|
64
|
+
claudeReason = !claudeModels.length ? "m365_no_claude_models" : corePort === M365_GATEWAY_PORT ? "m365_gateway_core_port_conflict" : null;
|
|
65
|
+
if (claudeReason === "m365_gateway_core_port_conflict") log("warn", `Claude gateway skipped: port ${M365_GATEWAY_PORT} belongs to the configured core service; M365 GPT routing remains available`);
|
|
66
|
+
if (claudeModels.length && !claudeReason) try {
|
|
37
67
|
const apiKey = ensureM365GatewayKey(options);
|
|
38
68
|
if (!gateway) {
|
|
39
69
|
const start = startGateway || (await import("./claude-gateway.mjs")).startClaudeGateway;
|
|
@@ -42,13 +72,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
42
72
|
if (closed || !enabled) { await opened.close();return null; }
|
|
43
73
|
gateway = opened;
|
|
44
74
|
}
|
|
45
|
-
|
|
46
|
-
const integration = configureClients ? null : await import("./claude-client-config.mjs");
|
|
47
|
-
const configure = configureClients || integration.configureClaudeClients;
|
|
48
|
-
const desktopManaged = integration ? await integration.inspectClaudeDesktopPolicy(options) : false;
|
|
49
|
-
if (closed || !enabled) return null;
|
|
50
|
-
clients = configure({ ...options, desktopManaged, baseUrl: `http://127.0.0.1:${gateway.port}`, apiKey, models: claudeModels });
|
|
51
|
-
} catch { clients = { code: "configuration_unavailable", app: "configuration_unavailable" };claudeReason = "m365_claude_config_unavailable"; }
|
|
75
|
+
await syncClaudeClients();
|
|
52
76
|
} catch (error) {
|
|
53
77
|
claudeReason = error.code === "EADDRINUSE" ? "m365_gateway_port_busy" : "m365_claude_setup_unavailable";
|
|
54
78
|
log("warn", `Claude setup unavailable: ${claudeReason}; M365 GPT routing is independent`);
|
|
@@ -123,13 +147,37 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
123
147
|
return {
|
|
124
148
|
github, current, snapshot, start: startM365, refresh: () => startM365(true),
|
|
125
149
|
selection: () => selection,
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
150
|
+
dashboardProviders() {
|
|
151
|
+
const state = snapshot(), service = githubClient.runtimeStatus?.() || {}, ms = state.m365;
|
|
152
|
+
return [
|
|
153
|
+
{ id: "github", name: "GitHub Copilot", generation: dashboardGeneration(github), enabled: true, state: service.token_cached ? "ready" : "unknown",
|
|
154
|
+
auth: { state: "unknown", token_cached: service.token_cached === true, expires_in_ms: service.token_expires_in_ms ?? null },
|
|
155
|
+
models: { count: githubRegistry?.models?.data?.length ?? null, source: githubRegistry?.source || "unknown" },
|
|
156
|
+
clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "github", state: "configured" }] },
|
|
157
|
+
{ id: "m365", name: "Microsoft 365", generation: m365 ? dashboardGeneration(m365) : 0, enabled, state: ms.state, reason: ms.reason,
|
|
158
|
+
auth: { state: ms.token_cached ? "authorized" : !enabled ? "disabled" : ms.reason ? "unavailable" : "unknown",
|
|
159
|
+
account: ms.account?.login || "", token_cached: ms.token_cached === true,
|
|
160
|
+
expires_in_ms: ms.token_expires_in_ms ?? null, checked_at: ms.token_checked_at || null },
|
|
161
|
+
models: { count: ms.models?.total ?? null, source: ms.models?.source || "unavailable", checked_at: ms.models?.refreshed_at || null },
|
|
162
|
+
clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "m365", state: selection.codex === "m365" ? ms.state : "standby" },
|
|
163
|
+
...[["code", "Claude Code"], ["app", "Claude App"]].map(([id, name]) => ({ id: `claude_${id}`, name,
|
|
164
|
+
selected: enabled, state: clients[id], gateway: gateway ? "running" : "unavailable", reason: claudeReason,
|
|
165
|
+
last_request_at: lastClients[`claude_${id}`] || null }))],
|
|
166
|
+
requests: ms.claude.requests },
|
|
167
|
+
];
|
|
168
|
+
},
|
|
169
|
+
async dashboardCatalog({ provider = selection.codex } = {}) {
|
|
170
|
+
if (provider === "github") return null;
|
|
171
|
+
if (provider !== "m365") throw Object.assign(new Error("Unknown provider"), { statusCode: 400 });
|
|
172
|
+
if (!enabled || !["darwin", "win32"].includes(platform)) throw unavailable(!enabled ? "m365_disabled" : "m365_unsupported");
|
|
173
|
+
if (!m365) throw unavailable(reason || "m365_not_ready");
|
|
174
|
+
await m365.refresh();
|
|
175
|
+
const eligible = new Set([...m365.models("gpt"), ...m365.models("claude")]);
|
|
176
|
+
return { source: "catalog", checkedAt: m365.snapshot().models.refreshed_at, upstreamHost: "Microsoft 365",
|
|
177
|
+
advertised: m365.catalog().length, models: publicModelCatalog(m365.catalog(), {
|
|
178
|
+
selectable: model => eligible.has(model),
|
|
179
|
+
clients: model => !eligible.has(model) ? [] : model.publisher?.toLowerCase() === "anthropic" ? ["claude_code", "claude_app"] : ["codex"],
|
|
180
|
+
}) };
|
|
133
181
|
},
|
|
134
182
|
track(target) {
|
|
135
183
|
if (target.id !== "m365") return undefined;
|
|
@@ -58,10 +58,10 @@ export function requestM365Token({ account, signal, env = process.env, spawnImpl
|
|
|
58
58
|
}
|
|
59
59
|
|
|
60
60
|
export function createM365Auth({ home, env = process.env, acquire = requestM365Token, now = Date.now } = {}) {
|
|
61
|
-
let cached = null, flight = null, generation = 0, lastError = null, retryAt = 0;
|
|
61
|
+
let cached = null, flight = null, generation = 0, lastError = null, retryAt = 0, checkedAt = null;
|
|
62
62
|
const snapshot = () => ({ token_cached: Boolean(cached && cached.expiresAt > now()),
|
|
63
63
|
token_expires_in_ms: cached ? Math.max(0, cached.expiresAt - now()) : null,
|
|
64
|
-
token_refresh_in_flight: Boolean(flight), reason: lastError,
|
|
64
|
+
token_refresh_in_flight: Boolean(flight), token_checked_at: checkedAt, reason: lastError,
|
|
65
65
|
account: cached ? { login: cached.account.login } : null });
|
|
66
66
|
function getToken({ signal } = {}) {
|
|
67
67
|
if (signal?.aborted) return Promise.reject(abortError(signal));
|
|
@@ -75,7 +75,7 @@ export function createM365Auth({ home, env = process.env, acquire = requestM365T
|
|
|
75
75
|
.then(result => {
|
|
76
76
|
if (current !== generation || controller.signal.aborted) throw abortError(controller.signal);
|
|
77
77
|
m365AccountKey(result.account);
|
|
78
|
-
cached = result;lastError = null;retryAt = 0;return result;
|
|
78
|
+
cached = result;lastError = null;retryAt = 0;checkedAt = new Date(now()).toISOString();return result;
|
|
79
79
|
}).catch(error => {
|
|
80
80
|
if (current === generation && !controller.signal.aborted) {
|
|
81
81
|
lastError = /^m365_[a-z_]+$/.test(error?.code || "") ? error.code : "m365_auth_failed";
|
|
@@ -101,5 +101,5 @@ export function createM365Auth({ home, env = process.env, acquire = requestM365T
|
|
|
101
101
|
entry.promise.then(value => finish(resolve, value), error => finish(reject, error));
|
|
102
102
|
});
|
|
103
103
|
}
|
|
104
|
-
return { getToken, snapshot, reset() { generation += 1;flight?.controller.abort();flight = null;cached = null;lastError = null;retryAt = 0; } };
|
|
104
|
+
return { getToken, snapshot, reset() { generation += 1;flight?.controller.abort();flight = null;cached = null;lastError = null;retryAt = 0;checkedAt = null; } };
|
|
105
105
|
}
|
package/src/providers/m365.mjs
CHANGED
|
@@ -12,6 +12,8 @@ import { requestOptionsEvidence } from "../response-failures.mjs";
|
|
|
12
12
|
import { status } from "../status.mjs";
|
|
13
13
|
import { redactDiagnosticText } from "../diagnostic-text.mjs";
|
|
14
14
|
import { removeNativeImageTools } from "../responses-image-tools.mjs";
|
|
15
|
+
import { resolveClaudeModel } from "../claude-models.mjs";
|
|
16
|
+
import { modelReasoningEfforts } from "../provider-metadata.mjs";
|
|
15
17
|
import { limitM365CacheTtl } from "./m365-messages-policy.mjs";
|
|
16
18
|
|
|
17
19
|
export const M365_API_BASE = "https://df.loki.delve.office.com/api/v1/llmapi";
|
|
@@ -23,7 +25,7 @@ const protocolError = (code, message, statusCode = 400) => Object.assign(new Err
|
|
|
23
25
|
|
|
24
26
|
export function m365Headers(token, { headers = {}, conversationId, stream = false } = {}) {
|
|
25
27
|
const out = { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: stream ? "text/event-stream" : "application/json",
|
|
26
|
-
"X-ClientType": "GitHub", "X-ClientVersion": "0.
|
|
28
|
+
"X-ClientType": "GitHub", "X-ClientVersion": "1.0.0", "X-Llm-Api-Version": "2026-09-28", "X-ClientScenario": "Code",
|
|
27
29
|
"X-ClientFeature": "LlmApiProxy", "X-ClientCorrelationId": randomUUID(), "X-ClientCallId": randomUUID() };
|
|
28
30
|
if (conversationId) out["X-ConversationId"] = conversationId;
|
|
29
31
|
for (const name of ["anthropic-version", "anthropic-beta"]) {
|
|
@@ -160,7 +162,7 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
|
|
|
160
162
|
|
|
161
163
|
function selectedModel(id, family) {
|
|
162
164
|
const models = m365Models(catalog, family);
|
|
163
|
-
const model =
|
|
165
|
+
const model = family === "claude" ? resolveClaudeModel(models, id) : models.find(entry => entry.id === id);
|
|
164
166
|
if (!model) throw protocolError("m365_model_unavailable", `Model ${String(id).slice(0, 128)} is not available from Microsoft 365. Select a model from its current catalog.`);
|
|
165
167
|
return model;
|
|
166
168
|
}
|
|
@@ -193,7 +195,12 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
|
|
|
193
195
|
responsesCompact(body, options) { return client.responses(body, options); },
|
|
194
196
|
chatCompletions() { throw protocolError("m365_protocol_unsupported", "Microsoft 365 Codex routing requires native Responses"); },
|
|
195
197
|
async messages(body, options = {}) {
|
|
198
|
+
if (catalog && now() - catalogAt >= SOFT_TTL_MS && !flight) void refresh().catch(() => {});
|
|
196
199
|
const model = selectedModel(body.model, "claude");
|
|
200
|
+
const efforts = modelReasoningEfforts(model);
|
|
201
|
+
if (body.output_config?.effort !== undefined && efforts && !efforts.includes(body.output_config.effort)) {
|
|
202
|
+
throw protocolError("m365_effort_unavailable", "The selected effort is not advertised by this model. Refresh its model list and select an available effort.");
|
|
203
|
+
}
|
|
197
204
|
const adjusted = limitM365CacheTtl(body);
|
|
198
205
|
if (adjusted.changed && !cacheTtlAdjustments) log("info", "Microsoft 365 supports 5m prompt caching; 1h cache retention is capped to 5m. Content and breakpoints are unchanged.");
|
|
199
206
|
cacheTtlAdjustments += adjusted.changed;
|
|
@@ -205,6 +212,7 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
|
|
|
205
212
|
return {
|
|
206
213
|
id: "m365", client, registry, auth, refresh, profileId: profile,
|
|
207
214
|
models: family => m365Models(catalog, family),
|
|
215
|
+
catalog: () => catalog?.data || [],
|
|
208
216
|
selectModel(body, { requestedModel, upstreamModel }) {
|
|
209
217
|
selectedModel(upstreamModel, "gpt");
|
|
210
218
|
if (requestedModel !== CODEX_AUTO_REVIEW_MODEL && body.service_tier === "priority") {
|
package/src/usage-analysis.mjs
CHANGED
|
@@ -7,7 +7,7 @@ const cache = new Map();
|
|
|
7
7
|
|
|
8
8
|
// Only bounded, settled-file aggregates survive. No record index or payload cache.
|
|
9
9
|
export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "" } = {}) {
|
|
10
|
-
const analytics = createUsageAnalytics({ timeZone, now });
|
|
10
|
+
const analytics = createUsageAnalytics({ timeZone, now, qualifyProviders: !provider });
|
|
11
11
|
const zone = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
|
|
12
12
|
const version = warn === console.error ? await usageSummaryVersion(filePath) : null;
|
|
13
13
|
const key = version === null ? null : `${version}\0${provider}\0${zone.resolvedOptions().timeZone}\0${zone.format(new Date(now))}`;
|
package/src/usage-analytics.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { cacheReadTokens, usageCacheHitRate } from "./usage-store.mjs";
|
|
1
|
+
import { cacheReadTokens, usageCacheHitRate, usageProvider } from "./usage-store.mjs";
|
|
2
2
|
|
|
3
3
|
const DAY_MS = 86400000;
|
|
4
4
|
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_hit_unknown_requests", "cache_hit_invalid_requests"];
|
|
7
7
|
|
|
8
|
-
export function createUsageAnalytics({ timeZone = "UTC", now = Date.now() } = {}) {
|
|
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" });
|
|
10
10
|
const today = formatter.format(new Date(now));
|
|
11
11
|
const end = Date.parse(`${today}T00:00:00Z`);
|
|
@@ -51,7 +51,7 @@ export function createUsageAnalytics({ timeZone = "UTC", now = Date.now() } = {}
|
|
|
51
51
|
let point = dates.get(date);
|
|
52
52
|
if (!point) { point = { requests: 0, byModel: new Map() }; dates.set(date, point); }
|
|
53
53
|
add(point, summary.totals);
|
|
54
|
-
const model = String(record.model || "unknown").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 100);
|
|
54
|
+
const model = String(qualifyProviders ? `${usageProvider(record)} / ${record.model || "unknown"}` : record.model || "unknown").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 100);
|
|
55
55
|
if (!models.has(model) && models.size >= MAX_MODELS) { modelsTruncated = true; return; }
|
|
56
56
|
models.add(model);
|
|
57
57
|
if (!point.byModel.has(model)) point.byModel.set(model, { requests: 0 });
|
package/src/usage-store.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isProviderId } from "./provider-metadata.mjs";
|
|
1
2
|
import fs from "node:fs";
|
|
2
3
|
import { markRequestObservation } from "./stream-performance.mjs";
|
|
3
4
|
import os from "node:os";
|
|
@@ -113,14 +114,14 @@ export function buildResponsesUsageRecord({ surface = "responses", mode, model,
|
|
|
113
114
|
});
|
|
114
115
|
}
|
|
115
116
|
|
|
116
|
-
export function buildMessagesUsageRecord({ model, responseId, usage, mode, client = "claude" } = {}) {
|
|
117
|
+
export function buildMessagesUsageRecord({ model, responseId, usage, mode, client = "claude", provider = "m365" } = {}) {
|
|
117
118
|
if (!usage || typeof usage !== "object") return null;
|
|
118
119
|
const count = key => Number.isFinite(usage[key]) && usage[key] >= 0 ? usage[key] : undefined;
|
|
119
120
|
const uncached = count("input_tokens"), read = count("cache_read_input_tokens"), written = count("cache_creation_input_tokens");
|
|
120
121
|
const input = uncached === undefined ? undefined : uncached + (read || 0) + (written || 0);
|
|
121
122
|
const output = count("output_tokens");
|
|
122
123
|
if (input === undefined && output === undefined) return null;
|
|
123
|
-
return compactObject({ ts: new Date().toISOString(), provider
|
|
124
|
+
return compactObject({ ts: new Date().toISOString(), provider, surface: "messages", client, mode, model, response_id: responseId,
|
|
124
125
|
usage: compactObject({ input_tokens: input, output_tokens: output, cached_input_tokens: read,
|
|
125
126
|
cache_write_input_tokens: written, total_tokens: input !== undefined && output !== undefined ? input + output : undefined,
|
|
126
127
|
reasoning_output_tokens: numberOrUndefined(usage.output_tokens_details?.thinking_tokens) }),
|
|
@@ -278,16 +279,21 @@ function addUsageTotals(target, usage = {}) {
|
|
|
278
279
|
}
|
|
279
280
|
|
|
280
281
|
export function usageProvider(record) {
|
|
281
|
-
return record.provider === undefined
|
|
282
|
+
return record.provider === undefined ? "github" : isProviderId(record.provider) ? record.provider : "unknown";
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export function usageModelGroups(summary) {
|
|
286
|
+
const mixed = !summary.provider_filter && Object.values(summary.providers || {}).filter(count => count > 0).length > 1;
|
|
287
|
+
return mixed ? summary.bySourceModel || summary.byModel || {} : summary.byModel || {};
|
|
282
288
|
}
|
|
283
289
|
|
|
284
290
|
export function summarizeUsage(records, { provider = "" } = {}) {
|
|
285
|
-
if (provider && !
|
|
286
|
-
const summary = { requests: 0, totals: {}, byModel: {}, providers: { github: 0, m365: 0, unknown: 0 }, ...(provider ? { provider_filter: provider } : {}) };
|
|
291
|
+
if (provider && !isProviderId(provider)) throw new Error("Usage provider must be a valid provider ID");
|
|
292
|
+
const summary = { requests: 0, totals: {}, byModel: {}, bySourceModel: {}, providers: { github: 0, m365: 0, unknown: 0 }, ...(provider ? { provider_filter: provider } : {}) };
|
|
287
293
|
for (const record of records) {
|
|
288
294
|
const source = usageProvider(record);
|
|
289
295
|
if (provider && provider !== source) continue;
|
|
290
|
-
summary.providers[source]
|
|
296
|
+
summary.providers[source] = (summary.providers[source] || 0) + 1;
|
|
291
297
|
summary.requests += 1;
|
|
292
298
|
addUsageTotals(summary.totals, record.usage);
|
|
293
299
|
if (record.copilot_usage) {
|
|
@@ -301,16 +307,19 @@ export function summarizeUsage(records, { provider = "" } = {}) {
|
|
|
301
307
|
addUsageTotals(modelTotals, record.usage);
|
|
302
308
|
const input = record.usage?.input_tokens;
|
|
303
309
|
const cached = cacheReadTokens(record.usage || {});
|
|
304
|
-
if (!Number.isFinite(input) || input < 0 || !Number.isFinite(cached) || cached < 0 || cached > input) {
|
|
305
|
-
summary.totals.cache_hit_unknown_requests = (summary.totals.cache_hit_unknown_requests || 0) + 1;
|
|
306
|
-
modelTotals.cache_hit_unknown_requests = (modelTotals.cache_hit_unknown_requests || 0) + 1;
|
|
307
|
-
}
|
|
308
310
|
const cacheCounts = [record.usage?.cached_input_tokens, record.usage?.cache_read_input_tokens];
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
||
|
|
312
|
-
|
|
313
|
-
|
|
311
|
+
const unknown = !Number.isFinite(input) || input < 0 || !Number.isFinite(cached) || cached < 0 || cached > input;
|
|
312
|
+
const invalid = (input != null && (!Number.isFinite(input) || input < 0))
|
|
313
|
+
|| cacheCounts.some(value => value != null && (!Number.isFinite(value) || value < 0))
|
|
314
|
+
|| (Number.isFinite(input) && Number.isFinite(cached) && cached > input);
|
|
315
|
+
const qualified = `${source} / ${model}`;
|
|
316
|
+
if (!Object.hasOwn(summary.bySourceModel, qualified)) summary.bySourceModel[qualified] = { requests: 0 };
|
|
317
|
+
const sourceTotals = summary.bySourceModel[qualified];
|
|
318
|
+
sourceTotals.requests++;
|
|
319
|
+
addUsageTotals(sourceTotals, record.usage);
|
|
320
|
+
for (const target of [summary.totals, modelTotals, sourceTotals]) {
|
|
321
|
+
if (unknown) target.cache_hit_unknown_requests = (target.cache_hit_unknown_requests || 0) + 1;
|
|
322
|
+
if (invalid) target.cache_hit_invalid_requests = (target.cache_hit_invalid_requests || 0) + 1;
|
|
314
323
|
}
|
|
315
324
|
}
|
|
316
325
|
return summary;
|
|
@@ -330,6 +339,10 @@ async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord
|
|
|
330
339
|
if (!Object.hasOwn(summary.byModel, model)) Object.defineProperty(summary.byModel, model, { value: { requests: 0 }, enumerable: true, configurable: true, writable: true });
|
|
331
340
|
addUsageTotals(summary.byModel[model], values);
|
|
332
341
|
}
|
|
342
|
+
for (const [model, values] of Object.entries(one.bySourceModel)) {
|
|
343
|
+
if (!Object.hasOwn(summary.bySourceModel, model)) summary.bySourceModel[model] = {};
|
|
344
|
+
addUsageTotals(summary.bySourceModel[model], values);
|
|
345
|
+
}
|
|
333
346
|
}
|
|
334
347
|
}
|
|
335
348
|
return summary;
|
|
@@ -358,7 +371,7 @@ export async function usageSummaryVersion(filePath) {
|
|
|
358
371
|
}
|
|
359
372
|
|
|
360
373
|
export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord, provider = "" } = {}) {
|
|
361
|
-
if (provider && !
|
|
374
|
+
if (provider && !isProviderId(provider)) throw new Error("Usage provider must be a valid provider ID");
|
|
362
375
|
if (onRecord || warn !== console.error) return summarizeUsageLogFiles(filePath, { warn, onRecord, provider });
|
|
363
376
|
const fileVersion = await usageSummaryVersion(filePath);
|
|
364
377
|
const version = fileVersion === null ? null : `${fileVersion}\0${provider}`;
|
package/src/usage.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { cliOutputFormat, cliOutputWidth, formatResponsiveCliTable, terminalCell } from "./cli-table.mjs";
|
|
2
|
-
import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageLogPath } from "./usage-store.mjs";
|
|
2
|
+
import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageLogPath, usageModelGroups } from "./usage-store.mjs";
|
|
3
3
|
|
|
4
4
|
export {
|
|
5
5
|
usageSummaryVersion,
|
|
@@ -9,6 +9,7 @@ export {
|
|
|
9
9
|
buildResponsesUsageRecord,
|
|
10
10
|
buildMessagesUsageRecord,
|
|
11
11
|
usageProvider,
|
|
12
|
+
usageModelGroups,
|
|
12
13
|
recordUsage,
|
|
13
14
|
recordResponsesUsage,
|
|
14
15
|
flushUsageWritesForTests,
|
|
@@ -33,10 +34,16 @@ function cacheHitPercent(usage) {
|
|
|
33
34
|
return rate === null ? "—" : `${usage.cache_hit_unknown_requests > 0 ? "~" : ""}${(rate * 100).toFixed(1)}%`;
|
|
34
35
|
}
|
|
35
36
|
|
|
37
|
+
function providerSummaryLines(summary) {
|
|
38
|
+
if (summary.provider_filter) return [`Provider: ${summary.provider_filter}`];
|
|
39
|
+
const sources = Object.entries(summary.providers || {}).filter(([, count]) => count > 0);
|
|
40
|
+
return sources.some(([id]) => id !== "github")
|
|
41
|
+
? [`Providers: ${sources.map(([id, count]) => `${id} ${fmt(count)}`).join(" / ")} (combined totals; use --provider to separate)`] : [];
|
|
42
|
+
}
|
|
43
|
+
|
|
36
44
|
function formatPlainUsageSummary(summary, filePath, { sanitize = false } = {}) {
|
|
37
45
|
const lines = [`Usage log: ${filePath}`];
|
|
38
|
-
|
|
39
|
-
else if (summary.providers?.m365) lines.push(`Providers: GitHub ${fmt(summary.providers.github)} / M365 ${fmt(summary.providers.m365)} (combined totals; use --provider to separate)`);
|
|
46
|
+
lines.push(...providerSummaryLines(summary));
|
|
40
47
|
if (summary.requests === 0) {
|
|
41
48
|
lines.push("No usage records yet.");
|
|
42
49
|
return (sanitize ? lines.map((line) => terminalCell(line, { fallback: "" })) : lines).join("\n");
|
|
@@ -48,7 +55,7 @@ function formatPlainUsageSummary(summary, filePath, { sanitize = false } = {}) {
|
|
|
48
55
|
"",
|
|
49
56
|
"By model:",
|
|
50
57
|
);
|
|
51
|
-
for (const [model, row] of Object.entries(summary
|
|
58
|
+
for (const [model, row] of Object.entries(usageModelGroups(summary))) {
|
|
52
59
|
lines.push(` ${model}: requests=${fmt(row.requests)} input=${fmt(row.input_tokens)} cache_read=${fmt(cacheReadTokens(row))} output=${fmt(row.output_tokens)} total=${fmt(row.total_tokens)} cache_hit=${cacheHitPercent(row)}`);
|
|
53
60
|
}
|
|
54
61
|
return (sanitize ? lines.map((line) => terminalCell(line, { fallback: "" })) : lines).join("\n");
|
|
@@ -89,7 +96,7 @@ function formatTableUsageSummary(summary, filePath, output) {
|
|
|
89
96
|
{ key: "total", label: "TOTAL", align: "right" },
|
|
90
97
|
];
|
|
91
98
|
const compactColumns = [columns[0], columns[1], columns[5]];
|
|
92
|
-
const modelUsage = Object.entries(summary
|
|
99
|
+
const modelUsage = Object.entries(usageModelGroups(summary))
|
|
93
100
|
.map(([model, row]) => ({ model, row }))
|
|
94
101
|
.sort(compareModelUsage);
|
|
95
102
|
const totalUsage = { requests: summary.requests, ...summary.totals };
|
|
@@ -107,8 +114,7 @@ function formatTableUsageSummary(summary, filePath, output) {
|
|
|
107
114
|
} else {
|
|
108
115
|
table.compact = false;
|
|
109
116
|
}
|
|
110
|
-
const lines = [`Usage log: ${safePath}`, ...(summary
|
|
111
|
-
: summary.providers?.m365 ? [`Providers: GitHub ${fmt(summary.providers.github)} / M365 ${fmt(summary.providers.m365)} (combined totals; use --provider to separate)`] : []), "", table.output];
|
|
117
|
+
const lines = [`Usage log: ${safePath}`, ...providerSummaryLines(summary), "", table.output];
|
|
112
118
|
if (table.compact) {
|
|
113
119
|
lines.push(
|
|
114
120
|
"",
|