codex-copilot-dx 0.10.1 → 1.1.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 +18 -17
- package/bin/cli.mjs +24 -3
- package/docs/ARCHITECTURE.md +60 -14
- package/docs/README.md +3 -0
- package/docs/REFERENCE.md +186 -45
- package/package.json +2 -2
- package/src/adapter.mjs +19 -4
- package/src/browser-launch.mjs +22 -0
- package/src/claude-client-config.mjs +22 -5
- package/src/claude-gateway.mjs +30 -8
- package/src/claude-models.mjs +26 -0
- package/src/cli-animation.mjs +1 -1
- package/src/cli-image.mjs +3 -0
- package/src/cli-m365.mjs +1 -1
- package/src/cli-options.mjs +11 -6
- package/src/cli-table.mjs +1 -1
- package/src/client-integration.mjs +5 -1
- package/src/dashboard/console.js +141 -0
- package/src/dashboard/index.html +105 -52
- package/src/dashboard/language.js +103 -0
- package/src/dashboard/refresh.js +2 -1
- package/src/dashboard/status.js +60 -29
- package/src/dashboard/ui.css +49 -0
- package/src/dashboard/ui.js +113 -26
- package/src/dashboard-api.mjs +72 -7
- package/src/dashboard.mjs +1 -0
- package/src/image-mcp.mjs +9 -6
- package/src/live-models.mjs +11 -3
- package/src/log.mjs +13 -11
- package/src/m365-settings.mjs +0 -2
- package/src/native-prediction-recovery.mjs +1 -0
- package/src/native-prediction.mjs +6 -2
- package/src/observability.mjs +8 -1
- package/src/optional-routes.mjs +2 -2
- package/src/provider-metadata.mjs +21 -0
- package/src/provider-runtime.mjs +80 -26
- package/src/providers/m365-auth.mjs +4 -4
- package/src/providers/m365.mjs +10 -2
- package/src/response-failures.mjs +1 -1
- package/src/service-control.mjs +60 -0
- package/src/startup-ui.mjs +4 -3
- package/src/terminal-console.mjs +87 -0
- package/src/usage-analysis.mjs +1 -1
- package/src/usage-analytics.mjs +3 -3
- package/src/usage-store.mjs +40 -17
- package/src/usage.mjs +14 -7
- package/src/user-settings.mjs +21 -0
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
|
|
5
|
+
import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey } 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 });
|
|
@@ -15,11 +16,36 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
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:${corePort}/anthropic`,
|
|
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,33 +54,29 @@ 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 ? "m365_no_claude_models" :
|
|
36
|
-
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`);
|
|
64
|
+
claudeReason = !claudeModels.length ? "m365_no_claude_models" : null;
|
|
37
65
|
if (claudeModels.length && !claudeReason) try {
|
|
38
66
|
const apiKey = ensureM365GatewayKey(options);
|
|
39
67
|
if (!gateway) {
|
|
40
|
-
const start = startGateway || (await import("./claude-gateway.mjs")).
|
|
41
|
-
const opened = await start({ provider: m365, apiKey, env, log,
|
|
68
|
+
const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
|
|
69
|
+
const opened = await start({ provider: m365, apiKey, port: corePort, env, log,
|
|
42
70
|
onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
|
|
43
71
|
if (closed || !enabled) { await opened.close();return null; }
|
|
44
72
|
gateway = opened;
|
|
45
73
|
}
|
|
46
|
-
|
|
47
|
-
const integration = configureClients ? null : await import("./claude-client-config.mjs");
|
|
48
|
-
const configure = configureClients || integration.configureClaudeClients;
|
|
49
|
-
const desktopManaged = integration ? await integration.inspectClaudeDesktopPolicy(options) : false;
|
|
50
|
-
if (closed || !enabled) return null;
|
|
51
|
-
clients = configure({ ...options, desktopManaged, baseUrl: `http://127.0.0.1:${gateway.port}`, apiKey, models: claudeModels });
|
|
52
|
-
} catch { clients = { code: "configuration_unavailable", app: "configuration_unavailable" };claudeReason = "m365_claude_config_unavailable"; }
|
|
74
|
+
await syncClaudeClients();
|
|
53
75
|
} catch (error) {
|
|
54
76
|
claudeReason = error.code === "EADDRINUSE" ? "m365_gateway_port_busy" : "m365_claude_setup_unavailable";
|
|
55
77
|
log("warn", `Claude setup unavailable: ${claudeReason}; M365 GPT routing is independent`);
|
|
56
78
|
}
|
|
57
|
-
reason = null;log("ok", `Microsoft 365 ready: ${claudeModels.length} Claude, ${m365.models("gpt").length} GPT models${gateway ? `; Claude
|
|
79
|
+
reason = null;log("ok", `Microsoft 365 ready: ${claudeModels.length} Claude, ${m365.models("gpt").length} GPT models${gateway ? `; Claude at http://127.0.0.1:${corePort}/anthropic` : ""}`);
|
|
58
80
|
return m365;
|
|
59
81
|
})().catch(error => {
|
|
60
82
|
reason = /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : error.code === "EADDRINUSE" ? "m365_gateway_port_busy" : "m365_unavailable";
|
|
@@ -70,7 +92,8 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
70
92
|
reason: reason || m365?.snapshot().reason || null,
|
|
71
93
|
preference: selection.m365 || null,
|
|
72
94
|
active_requests: activeM365Requests,
|
|
73
|
-
claude: { gateway: gateway ? "running" : "unavailable", reason: claudeReason, port: gateway
|
|
95
|
+
claude: { gateway: gateway ? "running" : "unavailable", reason: claudeReason, port: gateway ? corePort : null,
|
|
96
|
+
base_url: gateway ? `http://127.0.0.1:${corePort}/anthropic` : null, clients: { ...clients },
|
|
74
97
|
observed_clients: { ...lastClients }, requests: gateway?.snapshot?.() || null } } });
|
|
75
98
|
|
|
76
99
|
function current() {
|
|
@@ -102,12 +125,12 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
102
125
|
selection = next;return snapshot();
|
|
103
126
|
}
|
|
104
127
|
async function disable(remove) {
|
|
105
|
-
if (
|
|
106
|
-
throw Object.assign(new Error("Microsoft 365 requests are active; finish them before removing its profile"), { code: "m365_profile_busy", statusCode: 409 });
|
|
128
|
+
if (activeM365Requests > 0 || gateway?.snapshot?.().active > 0) {
|
|
129
|
+
throw Object.assign(new Error("Microsoft 365 requests are active; finish them before disabling or removing its profile"), { code: "m365_profile_busy", statusCode: 409 });
|
|
107
130
|
}
|
|
108
131
|
await switchSource("github");
|
|
109
132
|
updateM365Settings({ enabled: false }, options);enabled = false;
|
|
110
|
-
|
|
133
|
+
await gateway?.close();gateway = null;m365?.close();
|
|
111
134
|
await pending;m365 = null;
|
|
112
135
|
const restore = restoreClients || (await import("./claude-client-config.mjs")).restoreClaudeClients;
|
|
113
136
|
const result = restore(options);clients = { code: result.preserved ? "preserved" : "restored", app: result.preserved ? "preserved" : "restored" };
|
|
@@ -123,14 +146,45 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
123
146
|
}
|
|
124
147
|
return {
|
|
125
148
|
github, current, snapshot, start: startM365, refresh: () => startM365(true),
|
|
149
|
+
handleClaude(req, res) {
|
|
150
|
+
if (!enabled || !gateway?.handle) {
|
|
151
|
+
res.writeHead(503, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
152
|
+
res.end(JSON.stringify({ type: "error", error: { type: "api_error", code: claudeReason || reason || "m365_claude_unavailable", message: "Claude is unavailable; check the model service settings." } }));return;
|
|
153
|
+
}
|
|
154
|
+
return gateway.handle(req, res);
|
|
155
|
+
},
|
|
126
156
|
selection: () => selection,
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
157
|
+
dashboardProviders() {
|
|
158
|
+
const state = snapshot(), service = githubClient.runtimeStatus?.() || {}, ms = state.m365;
|
|
159
|
+
return [
|
|
160
|
+
{ id: "github", name: "GitHub Copilot", generation: dashboardGeneration(github), enabled: true, state: service.token_cached ? "ready" : "unknown",
|
|
161
|
+
auth: { state: "unknown", token_cached: service.token_cached === true, expires_in_ms: service.token_expires_in_ms ?? null },
|
|
162
|
+
models: { count: githubRegistry?.models?.data?.length ?? null, source: githubRegistry?.source || "unknown" },
|
|
163
|
+
clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "github", state: "configured" }] },
|
|
164
|
+
{ id: "m365", name: "Microsoft 365", generation: m365 ? dashboardGeneration(m365) : 0, enabled, state: ms.state, reason: ms.reason,
|
|
165
|
+
auth: { state: ms.token_cached ? "authorized" : !enabled ? "disabled" : ms.reason ? "unavailable" : "unknown",
|
|
166
|
+
account: ms.account?.login || "", token_cached: ms.token_cached === true,
|
|
167
|
+
expires_in_ms: ms.token_expires_in_ms ?? null, checked_at: ms.token_checked_at || null },
|
|
168
|
+
models: { count: ms.models?.total ?? null, source: ms.models?.source || "unavailable", checked_at: ms.models?.refreshed_at || null },
|
|
169
|
+
clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "m365", state: selection.codex === "m365" ? ms.state : "standby" },
|
|
170
|
+
...[["code", "Claude Code"], ["app", "Claude App"]].map(([id, name]) => ({ id: `claude_${id}`, name,
|
|
171
|
+
selected: enabled, state: clients[id], gateway: gateway ? "running" : "unavailable", reason: claudeReason,
|
|
172
|
+
last_request_at: lastClients[`claude_${id}`] || null }))],
|
|
173
|
+
requests: ms.claude.requests, request_scope: "Claude Messages" },
|
|
174
|
+
];
|
|
175
|
+
},
|
|
176
|
+
async dashboardCatalog({ provider = selection.codex } = {}) {
|
|
177
|
+
if (provider === "github") return null;
|
|
178
|
+
if (provider !== "m365") throw Object.assign(new Error("Unknown provider"), { statusCode: 400 });
|
|
179
|
+
if (!enabled || !["darwin", "win32"].includes(platform)) throw unavailable(!enabled ? "m365_disabled" : "m365_unsupported");
|
|
180
|
+
if (!m365) throw unavailable(reason || "m365_not_ready");
|
|
181
|
+
await m365.refresh();
|
|
182
|
+
const eligible = new Set([...m365.models("gpt"), ...m365.models("claude")]);
|
|
183
|
+
return { source: "catalog", checkedAt: m365.snapshot().models.refreshed_at, upstreamHost: "Microsoft 365",
|
|
184
|
+
advertised: m365.catalog().length, models: publicModelCatalog(m365.catalog(), {
|
|
185
|
+
selectable: model => eligible.has(model),
|
|
186
|
+
clients: model => !eligible.has(model) ? [] : model.publisher?.toLowerCase() === "anthropic" ? ["claude_code", "claude_app"] : ["codex"],
|
|
187
|
+
}) };
|
|
134
188
|
},
|
|
135
189
|
track(target) {
|
|
136
190
|
if (target.id !== "m365") return undefined;
|
|
@@ -175,6 +229,6 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
175
229
|
throw new Error("Unknown M365 action");
|
|
176
230
|
});
|
|
177
231
|
},
|
|
178
|
-
async close() { closed = true;enabled = false;
|
|
232
|
+
async close() { closed = true;enabled = false;await gateway?.close();gateway = null;m365?.close();await pending; },
|
|
179
233
|
};
|
|
180
234
|
}
|
|
@@ -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") {
|
|
@@ -141,7 +141,7 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
|
|
|
141
141
|
return {
|
|
142
142
|
record(details) {
|
|
143
143
|
all.record(details);
|
|
144
|
-
const category = ["responses", "responses_compact"].includes(details.route) ? "inference"
|
|
144
|
+
const category = ["responses", "responses_compact", "messages", "messages_count_tokens"].includes(details.route) ? "inference"
|
|
145
145
|
: details.route === "image_mcp" && details.http_status === 405 ? "protocol"
|
|
146
146
|
: details.route === "not_found" ? "route" : "other";
|
|
147
147
|
counts[category]++;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { readUserSettings, servicePreferences, writeServicePreference, terminalAnimationPreference,
|
|
2
|
+
writeTerminalAnimationTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib } from "./user-settings.mjs";
|
|
3
|
+
import { readImageProviderConfig } from "./image-provider-config.mjs";
|
|
4
|
+
import { readPredictionSettings } from "./native-prediction-profile.mjs";
|
|
5
|
+
import { cacheRuntimeSnapshot, cleanRuntimeCaches, setHistoryCacheLimit } from "./cache-control.mjs";
|
|
6
|
+
import { isTerminalAnimationTheme } from "./terminal-animation.mjs";
|
|
7
|
+
|
|
8
|
+
export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
|
|
9
|
+
readImages = () => readImageProviderConfig({ env, home }), readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
|
|
10
|
+
const options = { env, home };
|
|
11
|
+
let serial = Promise.resolve();
|
|
12
|
+
function snapshot() {
|
|
13
|
+
readUserSettings({ ...options, strict: true });
|
|
14
|
+
const saved = servicePreferences(options), prediction = clientIntegration?.snapshot().prediction;
|
|
15
|
+
let imageConfigured = false, predictionConfigured = false;
|
|
16
|
+
try { imageConfigured = Boolean(readImages()); } catch {}
|
|
17
|
+
try { predictionConfigured = readPrediction().enabled === true; } catch {}
|
|
18
|
+
return { source: "service_settings", saved, theme: terminalAnimationPreference(options).theme,
|
|
19
|
+
effective: {
|
|
20
|
+
terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
|
|
21
|
+
state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
|
|
22
|
+
open_webui: { value: saved.open_webui, state: "next_start" },
|
|
23
|
+
image_enabled: { value: saved.image_enabled && imageConfigured, state: imageConfigured ? "next_call" : "needs_setup", configured: imageConfigured },
|
|
24
|
+
prediction_enabled: { value: prediction?.active === true, state: !predictionConfigured ? "needs_setup"
|
|
25
|
+
: prediction?.environment?.status === "needs_app_relaunch" ? "needs_app_relaunch" : prediction?.bridge !== "running" ? "needs_service_restart" : "next_config_request", configured: predictionConfigured },
|
|
26
|
+
}, history: { ...responseHistoryLimitPreference(options), ...cacheRuntimeSnapshot().response_history },
|
|
27
|
+
providers: providerRuntime?.snapshot() || null, terminal: terminal?.snapshot?.() || null };
|
|
28
|
+
}
|
|
29
|
+
async function apply(input) {
|
|
30
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
|
|
31
|
+
const allowed = { preference: ["action", "key", "value"], animation: ["action", "theme"],
|
|
32
|
+
history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
|
|
33
|
+
provider: ["action", "operation", "provider", "model", "auto_review_model"] }[input.action];
|
|
34
|
+
if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
|
|
35
|
+
if (input.action === "preference") {
|
|
36
|
+
writeServicePreference(input.key, input.value, options);
|
|
37
|
+
if (input.key === "prediction_enabled") clientIntegration?.setPredictionActive(input.value);
|
|
38
|
+
terminal?.apply?.({ ...servicePreferences(options) });
|
|
39
|
+
} else if (input.action === "animation") {
|
|
40
|
+
if (!isTerminalAnimationTheme(input.theme)) throw new Error("Select a listed animation theme");
|
|
41
|
+
writeTerminalAnimationTheme(input.theme, options);terminal?.apply?.({ theme: input.theme });
|
|
42
|
+
} else if (input.action === "prediction_fix") {
|
|
43
|
+
if (!clientIntegration) throw new Error("Prediction integration is unavailable");
|
|
44
|
+
await clientIntegration.fix();
|
|
45
|
+
} else if (input.action === "history_limit") {
|
|
46
|
+
if (responseHistoryLimitPreference(options).source === "environment") throw new Error("History limit is controlled by CCDX_RESPONSE_HISTORY_MAX_BYTES");
|
|
47
|
+
if (!Number.isSafeInteger(input.mib)) throw new Error("History limit must be an integer MiB value");
|
|
48
|
+
const before = cacheRuntimeSnapshot().response_history.maxBytes;
|
|
49
|
+
setHistoryCacheLimit(input.mib * 1024 * 1024);
|
|
50
|
+
try { writeResponseHistoryLimitMib(input.mib, options); } catch (error) { setHistoryCacheLimit(before);throw error; }
|
|
51
|
+
} else if (input.action === "history_clean") cleanRuntimeCaches({ history: true });
|
|
52
|
+
else {
|
|
53
|
+
if (!providerRuntime || !["on", "off", "switch"].includes(input.operation)) throw new Error("Invalid provider operation");
|
|
54
|
+
if (input.operation === "on" && env.CCDX_M365 === "0") throw new Error("Microsoft 365 is disabled by CCDX_M365=0");
|
|
55
|
+
await providerRuntime.action({ action: input.operation, provider: input.provider, model: input.model, auto_review_model: input.auto_review_model });
|
|
56
|
+
}
|
|
57
|
+
return snapshot();
|
|
58
|
+
}
|
|
59
|
+
return { snapshot, action(input) { const operation = serial.then(() => apply(input));serial = operation.catch(() => {});return operation; } };
|
|
60
|
+
}
|
package/src/startup-ui.mjs
CHANGED
|
@@ -16,8 +16,8 @@ const ATOM = [
|
|
|
16
16
|
export function startupBanner({ commandName = "ccdx", version, stream = process.stdout, env = process.env } = {}) {
|
|
17
17
|
const title = `${terminalCell(commandName)} v${terminalCell(version)} by Dale Xiao`;
|
|
18
18
|
const color = stream.isTTY === true && !Object.hasOwn(env, "NO_COLOR") && env.TERM !== "dumb";
|
|
19
|
-
if (!color || Number(stream.columns || 80) < 72) return `${title}\
|
|
20
|
-
const labels = new Map([[1, `${terminalCell(commandName).toUpperCase()} v${terminalCell(version)}`], [2, "by Dale Xiao"], [4, "Codex
|
|
19
|
+
if (!color || Number(stream.columns || 80) < 72) return `${title}\nLocal model services for Codex and Claude`;
|
|
20
|
+
const labels = new Map([[1, `${terminalCell(commandName).toUpperCase()} v${terminalCell(version)}`], [2, "by Dale Xiao"], [4, "Codex + Claude / local services"]]);
|
|
21
21
|
return ATOM.map((line, i) => `\x1b[38;2;166;245;168m${line}\x1b[0m${labels.has(i) ? ` ${labels.get(i)}` : ""}`).join("\n");
|
|
22
22
|
}
|
|
23
23
|
|
|
@@ -48,5 +48,6 @@ export function predictionStartupCheck(prediction) {
|
|
|
48
48
|
const summary = startupCheck(route === "unverified" ? "warn" : "info", "Prediction", route === "verified"
|
|
49
49
|
? "Bridge running; App route verified; suggestion not checked"
|
|
50
50
|
: "Bridge running; App route not verified; suggestion not checked");
|
|
51
|
-
|
|
51
|
+
const pause = prediction.active === false ? `\n${startupCheck("info", "Prediction", "Adaptation paused; existing trust/route retained")}` : "";
|
|
52
|
+
return (prediction.recovery ? `${summary}\n${startupCheck("info", "Recovery", `${prediction.recovery.attempts}/3 attempts used; persistent route ${prediction.persistence || "unknown"}`)}` : summary) + pause + details;
|
|
52
53
|
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { format, stripVTControlCharacters } from "node:util";
|
|
2
|
+
import { terminalCell } from "./terminal-text.mjs";
|
|
3
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
4
|
+
import { DEFAULT_TERMINAL_ANIMATION_THEME, TERMINAL_ANIMATION_THEMES, isTerminalAnimationTheme, renderTerminalAnimationFrame,
|
|
5
|
+
getTerminalAnimationCycleLength, getTerminalAnimationFrameDelay } from "./terminal-animation.mjs";
|
|
6
|
+
import { displayWidth } from "./cli-table.mjs";
|
|
7
|
+
|
|
8
|
+
const clear = "\r\x1b[2K";
|
|
9
|
+
const flagOff = value => /^(0|false|no|off)$/i.test(String(value || ""));
|
|
10
|
+
|
|
11
|
+
// A bounded status region, independent of file logging and inference delivery.
|
|
12
|
+
export function createTerminalConsole({ output = process.stdout, errorOutput = process.stderr, env = process.env,
|
|
13
|
+
snapshot = () => ({}), preferences = () => ({}), baseUrl = "", verbose = false,
|
|
14
|
+
timers = { setTimeout, clearTimeout }, now = Date.now } = {}) {
|
|
15
|
+
let running = false, timer = null, lines = 0, active = 0, frame = 0, lastRead = 0, data = {};
|
|
16
|
+
let notices = 0, lastNotice = "", lastPrintedNotice = "", lastRender = "";
|
|
17
|
+
let current = { theme: DEFAULT_TERMINAL_ANIMATION_THEME, terminal_animation_enabled: true };
|
|
18
|
+
let frameDelay = 1000;
|
|
19
|
+
const tty = output.isTTY === true && errorOutput.isTTY === true && (!env.CI || flagOff(env.CI)) && env.TERM !== "dumb";
|
|
20
|
+
const supported = () => tty && (Number(output.columns) || 80) >= 40;
|
|
21
|
+
const resized = () => { if (lines) output.write("\n");lines = 0;lastRender = "";frame = 0; };
|
|
22
|
+
output.on?.("resize", resized);
|
|
23
|
+
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
|
|
24
|
+
const clip = (value, width) => {
|
|
25
|
+
let text = "";
|
|
26
|
+
for (const { segment } of segmenter.segment(terminalCell(value, { fallback: "" }))) {
|
|
27
|
+
if (displayWidth(text + segment) > width) break;text += segment;
|
|
28
|
+
}
|
|
29
|
+
return text;
|
|
30
|
+
};
|
|
31
|
+
const compact = value => new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 }).format(Number(value) || 0);
|
|
32
|
+
function render() {
|
|
33
|
+
if (!running || !supported() || verbose) { frameDelay = 1000;return; }
|
|
34
|
+
const width = Math.max(1, Math.min(160, Number(output.columns) || 80) - 1);
|
|
35
|
+
const usage = data.runtime_usage || {}, routes = data.requests?.by_route || {};
|
|
36
|
+
const outcomes = [data.stream_performance?.by_route?.responses, data.stream_performance?.by_route?.responses_compact, data.providers?.m365?.claude?.requests?.performance?.by_route?.messages]
|
|
37
|
+
.map(route => route?.terminal_outcomes?.totals || {});
|
|
38
|
+
const sum = key => outcomes.reduce((total, item) => total + (Number(item[key]) || 0), 0);
|
|
39
|
+
let motion = active ? "●" : "○";
|
|
40
|
+
frameDelay = 1000;
|
|
41
|
+
if (active && current.terminal_animation_enabled && !flagOff(env.CCDX_TERMINAL_ANIMATION) && width >= 24) {
|
|
42
|
+
frame %= getTerminalAnimationCycleLength(current.theme);
|
|
43
|
+
const metadata = TERMINAL_ANIMATION_THEMES.find(theme => theme.id === current.theme), index = metadata.startFrame + frame;
|
|
44
|
+
motion = renderTerminalAnimationFrame(current.theme, index);
|
|
45
|
+
if (Object.hasOwn(env, "NO_COLOR")) motion = stripVTControlCharacters(motion);
|
|
46
|
+
frame = (frame + 1) % getTerminalAnimationCycleLength(current.theme);
|
|
47
|
+
frameDelay = getTerminalAnimationFrameDelay(current.theme, index) + (frame === 0 ? metadata.loopPauseMs : 0);
|
|
48
|
+
}
|
|
49
|
+
const requests = ["responses", "responses_compact", "messages"].reduce((total, key) => total + (routes[key]?.total || 0), 0);
|
|
50
|
+
const body = [
|
|
51
|
+
`CCDX ${lastNotice ? "ATTENTION" : "READY"} / uptime ${Math.floor((data.uptime_ms || 0) / 60000)}m / ${baseUrl}`,
|
|
52
|
+
`This run · usage records ${usage.records || 0} · input ${compact(usage.input_tokens)} · cache read ${compact(usage.cached_input_tokens)} · output ${compact(usage.output_tokens)}${usage.partial_records ? " ~" : ""}`,
|
|
53
|
+
`Inference · ${requests} HTTP calls · active ${active} · done ${sum("completed")} · incomplete ${sum("incomplete")} · failed ${sum("failed")} · cancelled ${sum("cancelled")}`,
|
|
54
|
+
].map(line => clip(line, width));
|
|
55
|
+
const notice = lastNotice ? `${notices} notices / ${lastNotice}` : active ? "Working" : "Idle / details in WebUI";
|
|
56
|
+
body.push(width >= 24 ? `${motion} ${clip(notice, Math.max(0, width - displayWidth(stripVTControlCharacters(motion)) - 1))}` : clip(`${motion} ${notice}`, width));
|
|
57
|
+
const rendered = body.join("\n");
|
|
58
|
+
if (rendered === lastRender) return;
|
|
59
|
+
lastRender = rendered;
|
|
60
|
+
output.write(`${lines ? `\x1b[${lines - 1}A` : ""}${body.map(line => clear + line).join("\n")}\r`);
|
|
61
|
+
lines = 4;
|
|
62
|
+
}
|
|
63
|
+
function tick() {
|
|
64
|
+
if (!running) return;
|
|
65
|
+
if (now() - lastRead >= 1000 || !lastRead) {
|
|
66
|
+
try { data = snapshot();current = { ...current, ...preferences() };if (!isTerminalAnimationTheme(current.theme)) current.theme = DEFAULT_TERMINAL_ANIMATION_THEME; } catch {}
|
|
67
|
+
lastRead = now();
|
|
68
|
+
}
|
|
69
|
+
render();
|
|
70
|
+
timer = timers.setTimeout(tick, frameDelay);timer?.unref?.();
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
get enabled() { return supported() && !verbose; },
|
|
74
|
+
start() { if (running) return;running = true;tick(); },
|
|
75
|
+
beginRequest() { active++;let done = false;return () => { if (!done) { done = true;active = Math.max(0, active - 1); } }; },
|
|
76
|
+
log(method, args) {
|
|
77
|
+
const message = redactDiagnosticText(format(...args));
|
|
78
|
+
if (verbose) { (method === "error" || method === "warn" ? errorOutput : output).write(`${message}\n`);return; }
|
|
79
|
+
if (method !== "error" && method !== "warn" && !/^\[(WARN|ERR)\]/.test(message.trim())) return;
|
|
80
|
+
notices++;lastNotice = message.replace(/\s+/g, " ").slice(0, 240);
|
|
81
|
+
if (!supported() && lastNotice !== lastPrintedNotice) { errorOutput.write(`${lastNotice}\n`);lastPrintedNotice = lastNotice; }
|
|
82
|
+
},
|
|
83
|
+
snapshot() { return { notices, last_notice: lastNotice || null, mode: verbose ? "verbose" : supported() ? "status" : "plain" }; },
|
|
84
|
+
apply(value) { if (value.theme && value.theme !== current.theme) frame = 0;current = { ...current, ...value };lastRead = 0; },
|
|
85
|
+
cleanup() { running = false;if (timer) timers.clearTimeout(timer);timer = null;if (lines) output.write("\n");lines = 0;output.off?.("resize", resized); },
|
|
86
|
+
};
|
|
87
|
+
}
|
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";
|
|
@@ -23,6 +24,9 @@ let pendingRecords = 0;
|
|
|
23
24
|
let pendingBytes = 0;
|
|
24
25
|
let droppedRecords = 0;
|
|
25
26
|
let writeFailures = 0;
|
|
27
|
+
const runtimeUsage = { since: new Date().toISOString(), records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 };
|
|
28
|
+
|
|
29
|
+
export function runtimeUsageSnapshot() { return { ...runtimeUsage }; }
|
|
26
30
|
|
|
27
31
|
export function usageLoggingStats() {
|
|
28
32
|
return { pending_records: pendingRecords, pending_bytes: pendingBytes, dropped_records: droppedRecords,
|
|
@@ -113,14 +117,14 @@ export function buildResponsesUsageRecord({ surface = "responses", mode, model,
|
|
|
113
117
|
});
|
|
114
118
|
}
|
|
115
119
|
|
|
116
|
-
export function buildMessagesUsageRecord({ model, responseId, usage, mode, client = "claude" } = {}) {
|
|
120
|
+
export function buildMessagesUsageRecord({ model, responseId, usage, mode, client = "claude", provider = "m365" } = {}) {
|
|
117
121
|
if (!usage || typeof usage !== "object") return null;
|
|
118
122
|
const count = key => Number.isFinite(usage[key]) && usage[key] >= 0 ? usage[key] : undefined;
|
|
119
123
|
const uncached = count("input_tokens"), read = count("cache_read_input_tokens"), written = count("cache_creation_input_tokens");
|
|
120
124
|
const input = uncached === undefined ? undefined : uncached + (read || 0) + (written || 0);
|
|
121
125
|
const output = count("output_tokens");
|
|
122
126
|
if (input === undefined && output === undefined) return null;
|
|
123
|
-
return compactObject({ ts: new Date().toISOString(), provider
|
|
127
|
+
return compactObject({ ts: new Date().toISOString(), provider, surface: "messages", client, mode, model, response_id: responseId,
|
|
124
128
|
usage: compactObject({ input_tokens: input, output_tokens: output, cached_input_tokens: read,
|
|
125
129
|
cache_write_input_tokens: written, total_tokens: input !== undefined && output !== undefined ? input + output : undefined,
|
|
126
130
|
reasoning_output_tokens: numberOrUndefined(usage.output_tokens_details?.thinking_tokens) }),
|
|
@@ -179,7 +183,14 @@ function scheduleUsageWriteDrain() {
|
|
|
179
183
|
}
|
|
180
184
|
|
|
181
185
|
export function recordUsage(record) {
|
|
182
|
-
if (!record
|
|
186
|
+
if (!record) return Promise.resolve();
|
|
187
|
+
const usage = record.usage || {};
|
|
188
|
+
runtimeUsage.records++;
|
|
189
|
+
for (const [target, value] of [["input_tokens", usage.input_tokens], ["cached_input_tokens", cacheReadTokens(usage)], ["output_tokens", usage.output_tokens]]) {
|
|
190
|
+
if (Number.isFinite(value) && value >= 0) runtimeUsage[target] += value;
|
|
191
|
+
}
|
|
192
|
+
if (!Number.isFinite(usage.input_tokens) || !Number.isFinite(usage.output_tokens) || cacheReadTokens(usage) === undefined) runtimeUsage.partial_records++;
|
|
193
|
+
if (process.env.CCDX_DISABLE_USAGE === "1") return Promise.resolve();
|
|
183
194
|
const filePath = usageLogPath();
|
|
184
195
|
const line = `${JSON.stringify(record)}\n`;
|
|
185
196
|
const bytes = Buffer.byteLength(line);
|
|
@@ -278,16 +289,21 @@ function addUsageTotals(target, usage = {}) {
|
|
|
278
289
|
}
|
|
279
290
|
|
|
280
291
|
export function usageProvider(record) {
|
|
281
|
-
return record.provider === undefined
|
|
292
|
+
return record.provider === undefined ? "github" : isProviderId(record.provider) ? record.provider : "unknown";
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export function usageModelGroups(summary) {
|
|
296
|
+
const mixed = !summary.provider_filter && Object.values(summary.providers || {}).filter(count => count > 0).length > 1;
|
|
297
|
+
return mixed ? summary.bySourceModel || summary.byModel || {} : summary.byModel || {};
|
|
282
298
|
}
|
|
283
299
|
|
|
284
300
|
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 } : {}) };
|
|
301
|
+
if (provider && !isProviderId(provider)) throw new Error("Usage provider must be a valid provider ID");
|
|
302
|
+
const summary = { requests: 0, totals: {}, byModel: {}, bySourceModel: {}, providers: { github: 0, m365: 0, unknown: 0 }, ...(provider ? { provider_filter: provider } : {}) };
|
|
287
303
|
for (const record of records) {
|
|
288
304
|
const source = usageProvider(record);
|
|
289
305
|
if (provider && provider !== source) continue;
|
|
290
|
-
summary.providers[source]
|
|
306
|
+
summary.providers[source] = (summary.providers[source] || 0) + 1;
|
|
291
307
|
summary.requests += 1;
|
|
292
308
|
addUsageTotals(summary.totals, record.usage);
|
|
293
309
|
if (record.copilot_usage) {
|
|
@@ -301,16 +317,19 @@ export function summarizeUsage(records, { provider = "" } = {}) {
|
|
|
301
317
|
addUsageTotals(modelTotals, record.usage);
|
|
302
318
|
const input = record.usage?.input_tokens;
|
|
303
319
|
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
320
|
const cacheCounts = [record.usage?.cached_input_tokens, record.usage?.cache_read_input_tokens];
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
||
|
|
312
|
-
|
|
313
|
-
|
|
321
|
+
const unknown = !Number.isFinite(input) || input < 0 || !Number.isFinite(cached) || cached < 0 || cached > input;
|
|
322
|
+
const invalid = (input != null && (!Number.isFinite(input) || input < 0))
|
|
323
|
+
|| cacheCounts.some(value => value != null && (!Number.isFinite(value) || value < 0))
|
|
324
|
+
|| (Number.isFinite(input) && Number.isFinite(cached) && cached > input);
|
|
325
|
+
const qualified = `${source} / ${model}`;
|
|
326
|
+
if (!Object.hasOwn(summary.bySourceModel, qualified)) summary.bySourceModel[qualified] = { requests: 0 };
|
|
327
|
+
const sourceTotals = summary.bySourceModel[qualified];
|
|
328
|
+
sourceTotals.requests++;
|
|
329
|
+
addUsageTotals(sourceTotals, record.usage);
|
|
330
|
+
for (const target of [summary.totals, modelTotals, sourceTotals]) {
|
|
331
|
+
if (unknown) target.cache_hit_unknown_requests = (target.cache_hit_unknown_requests || 0) + 1;
|
|
332
|
+
if (invalid) target.cache_hit_invalid_requests = (target.cache_hit_invalid_requests || 0) + 1;
|
|
314
333
|
}
|
|
315
334
|
}
|
|
316
335
|
return summary;
|
|
@@ -330,6 +349,10 @@ async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord
|
|
|
330
349
|
if (!Object.hasOwn(summary.byModel, model)) Object.defineProperty(summary.byModel, model, { value: { requests: 0 }, enumerable: true, configurable: true, writable: true });
|
|
331
350
|
addUsageTotals(summary.byModel[model], values);
|
|
332
351
|
}
|
|
352
|
+
for (const [model, values] of Object.entries(one.bySourceModel)) {
|
|
353
|
+
if (!Object.hasOwn(summary.bySourceModel, model)) summary.bySourceModel[model] = {};
|
|
354
|
+
addUsageTotals(summary.bySourceModel[model], values);
|
|
355
|
+
}
|
|
333
356
|
}
|
|
334
357
|
}
|
|
335
358
|
return summary;
|
|
@@ -358,7 +381,7 @@ export async function usageSummaryVersion(filePath) {
|
|
|
358
381
|
}
|
|
359
382
|
|
|
360
383
|
export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord, provider = "" } = {}) {
|
|
361
|
-
if (provider && !
|
|
384
|
+
if (provider && !isProviderId(provider)) throw new Error("Usage provider must be a valid provider ID");
|
|
362
385
|
if (onRecord || warn !== console.error) return summarizeUsageLogFiles(filePath, { warn, onRecord, provider });
|
|
363
386
|
const fileVersion = await usageSummaryVersion(filePath);
|
|
364
387
|
const version = fileVersion === null ? null : `${fileVersion}\0${provider}`;
|