codex-copilot-dx 1.2.9 → 1.2.11
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 +2 -2
- package/docs/ARCHITECTURE.md +60 -4
- package/docs/REFERENCE.md +63 -2
- package/package.json +1 -1
- package/src/adapter.mjs +2 -1
- package/src/claude-gateway.mjs +2 -1
- package/src/cli-m365.mjs +5 -0
- package/src/dashboard/animation.js +186 -0
- package/src/dashboard/console.js +35 -14
- package/src/dashboard/flow.js +171 -0
- package/src/dashboard/index.html +68 -54
- package/src/dashboard/language.js +88 -43
- package/src/dashboard/status.js +27 -14
- package/src/dashboard/time.js +16 -0
- package/src/dashboard/tools.js +7 -3
- package/src/dashboard/ui.css +80 -16
- package/src/dashboard/ui.js +66 -208
- package/src/dashboard/updates.js +3 -3
- package/src/dashboard/usage.js +2 -2
- package/src/dashboard-api.mjs +4 -2
- package/src/dashboard.mjs +3 -0
- package/src/optional-routes.mjs +1 -1
- package/src/provider-descriptors.mjs +24 -0
- package/src/provider-runtime.mjs +10 -22
- package/src/providers/m365-catalog-diagnostic.mjs +38 -0
- package/src/providers/m365.mjs +8 -3
- package/src/request-application.mjs +15 -0
- package/src/stream-performance.mjs +33 -2
package/src/dashboard/usage.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
}).join(" ");
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
function create({ element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator, motionAllowed = () => false }) {
|
|
10
|
+
function create({ time, element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator, motionAllowed = () => false }) {
|
|
11
11
|
function usageValues(row) {
|
|
12
12
|
const rate = Number.isFinite(row.cache_hit_rate) && row.cache_hit_rate >= 0 && row.cache_hit_rate <= 1
|
|
13
13
|
? `${row.cache_hit_rate_partial ? "~" : ""}${(row.cache_hit_rate * 100).toFixed(1)}%` : "—";
|
|
@@ -236,7 +236,7 @@
|
|
|
236
236
|
if (data.analytics) renderAnalytics();
|
|
237
237
|
}
|
|
238
238
|
if (data.analytics) {
|
|
239
|
-
text("analytics-updated", "updated_time", { time:
|
|
239
|
+
text("analytics-updated", "updated_time", { time: time(Date.now()) });
|
|
240
240
|
}
|
|
241
241
|
}
|
|
242
242
|
return { applyUsage, renderUsageState, renderAnalytics, renderUsageTable, selectUsageDay, usageValues, setChartVisible, revealChart, stopMotion, get data() { return usageData; }, get selectedDate() { return selectedUsageDate; } };
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import os from "node:os";
|
|
2
2
|
import { isProviderId } from "./provider-metadata.mjs";
|
|
3
|
+
import { m365CatalogDiagnostic } from "./providers/m365-catalog-diagnostic.mjs";
|
|
3
4
|
import { m365NetworkDiagnostic } from "./providers/m365-network-diagnostic.mjs";
|
|
4
5
|
import { fetchLiveCopilotModels } from "./live-models.mjs";
|
|
5
6
|
import { authStatus } from "./auth-status.mjs";
|
|
@@ -125,6 +126,7 @@ function dashboardProviders(providerStateFn, authStatusFn) {
|
|
|
125
126
|
selection: { codex: entry.selection?.codex === true, models_required: entry.selection?.models_required === true },
|
|
126
127
|
state: code(entry.state) || "unknown", reason: code(entry.reason), generation: finite(entry.generation),
|
|
127
128
|
network_diagnostic: m365NetworkDiagnostic(entry.network_diagnostic),
|
|
129
|
+
catalog_diagnostic: m365CatalogDiagnostic(entry.catalog_diagnostic),
|
|
128
130
|
auth: { state: code(auth.state) || "unknown", account: label(auth.account), token_cached: auth.token_cached === true,
|
|
129
131
|
expires_in_ms: finite(auth.expires_in_ms), checked_at: label(auth.checked_at) || null },
|
|
130
132
|
models: { count: finite(entry.models?.count), source: code(entry.models?.source) || "unknown", checked_at: label(entry.models?.checked_at) || null },
|
|
@@ -310,8 +312,8 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
310
312
|
const message = /^m365_[a-z0-9_]+$/.test(error.code || "") ? `Model catalog unavailable / ${error.code}` : liveModelError(error);
|
|
311
313
|
if (!res.destroyed && !res.writableEnded) sendJson(res, error.statusCode || 502, { error: message,
|
|
312
314
|
diagnostic: { provider: provider || null, checked_at: new Date().toISOString(), message,
|
|
313
|
-
network: m365NetworkDiagnostic(error.network_diagnostic),
|
|
314
|
-
http_status: Number(/\bHTTP (\d{3})\b/.exec(message)?.[1]) || finite(error.statusCode),
|
|
315
|
+
network: m365NetworkDiagnostic(error.network_diagnostic), catalog: m365CatalogDiagnostic(error.catalog_diagnostic),
|
|
316
|
+
http_status: m365CatalogDiagnostic(error.catalog_diagnostic)?.http_status || Number(/\bHTTP (\d{3})\b/.exec(message)?.[1]) || finite(error.statusCode),
|
|
315
317
|
retry_after_ms: finite(error.retryAfterMs) } });
|
|
316
318
|
} finally { abort.cleanup(); }
|
|
317
319
|
return;
|
package/src/dashboard.mjs
CHANGED
|
@@ -6,11 +6,14 @@ const ASSETS = new Map([
|
|
|
6
6
|
["/ui.css", ["./dashboard/ui.css", "text/css; charset=utf-8"]],
|
|
7
7
|
["/theme.js", ["./dashboard/theme.js", "text/javascript; charset=utf-8"]],
|
|
8
8
|
["/language.js", ["./dashboard/language.js", "text/javascript; charset=utf-8"]],
|
|
9
|
+
["/animation.js", ["./dashboard/animation.js", "text/javascript; charset=utf-8"]],
|
|
9
10
|
["/ui.js", ["./dashboard/ui.js", "text/javascript; charset=utf-8"]],
|
|
10
11
|
["/console.js", ["./dashboard/console.js", "text/javascript; charset=utf-8"]],
|
|
11
12
|
["/updates.js", ["./dashboard/updates.js", "text/javascript; charset=utf-8"]],
|
|
13
|
+
["/time.js", ["./dashboard/time.js", "text/javascript; charset=utf-8"]],
|
|
12
14
|
["/status.js", ["./dashboard/status.js", "text/javascript; charset=utf-8"]],
|
|
13
15
|
["/activity.js", ["./dashboard/activity.js", "text/javascript; charset=utf-8"]],
|
|
16
|
+
["/flow.js", ["./dashboard/flow.js", "text/javascript; charset=utf-8"]],
|
|
14
17
|
["/usage.js", ["./dashboard/usage.js", "text/javascript; charset=utf-8"]],
|
|
15
18
|
["/refresh.js", ["./dashboard/refresh.js", "text/javascript; charset=utf-8"]],
|
|
16
19
|
["/icons.js", ["./dashboard/icons.js", "text/javascript; charset=utf-8"]],
|
package/src/optional-routes.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/activity.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js"]);
|
|
1
|
+
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js"]);
|
|
2
2
|
export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks"]);
|
|
3
3
|
|
|
4
4
|
export function isOptionalRoute(method, pathname) {
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Read-only presentation data; provider selection and account transactions stay in composition.
|
|
2
|
+
export function providerDescriptors({ state, githubRuntime, githubRegistry, githubClientConfigured,
|
|
3
|
+
githubGeneration, m365Generation, claudeClients, claudeReason, gatewayRunning, lastClients, definitions }) {
|
|
4
|
+
const ms = state.m365;
|
|
5
|
+
const projections = [
|
|
6
|
+
{ id: "github", generation: githubGeneration, enabled: true, state: githubRuntime.token_cached ? "ready" : "unknown",
|
|
7
|
+
auth: { state: "unknown", token_cached: githubRuntime.token_cached === true, expires_in_ms: githubRuntime.token_expires_in_ms ?? null },
|
|
8
|
+
models: { count: githubRegistry?.models?.data?.length ?? null, source: githubRegistry?.source || "unknown" },
|
|
9
|
+
clients: [{ id: "codex", name: "Codex App", selected: state.codex_provider === "github", state: githubClientConfigured ? "configured" : "unknown" }] },
|
|
10
|
+
{ id: "m365", generation: m365Generation, enabled: ms.enabled, state: ms.state, reason: ms.reason,
|
|
11
|
+
network_diagnostic: ms.network_diagnostic, catalog_diagnostic: ms.catalog_diagnostic,
|
|
12
|
+
auth: { state: ms.token_cached ? "authorized" : !ms.enabled ? "disabled" : ms.reason ? "unavailable" : "unknown",
|
|
13
|
+
account: ms.account?.login || "", tenant: ms.account?.tenant || "", selection_source: ms.account?.selection_source || null,
|
|
14
|
+
token_cached: ms.token_cached === true, expires_in_ms: ms.token_expires_in_ms ?? null, checked_at: ms.token_checked_at || null },
|
|
15
|
+
models: { count: ms.models?.total ?? null, source: ms.models?.source || "unavailable", checked_at: ms.models?.refreshed_at || null },
|
|
16
|
+
clients: [{ id: "codex", name: "Codex App", selected: state.codex_provider === "m365", state: state.codex_provider === "m365" ? ms.state : "standby" },
|
|
17
|
+
...[["code", "Claude Code"], ["app", "Claude App"]].map(([id, name]) => ({ id: `claude_${id}`, name,
|
|
18
|
+
selected: ms.enabled, state: claudeClients[id], gateway: gatewayRunning ? "running" : "unavailable", reason: claudeReason,
|
|
19
|
+
last_request_at: lastClients[`claude_${id}`] || null }))],
|
|
20
|
+
requests: ms.claude.requests, request_scope: "Claude Messages" },
|
|
21
|
+
];
|
|
22
|
+
return definitions.map(definition => ({ ...projections.find(source => source.id === definition.id),
|
|
23
|
+
id: definition.id, name: definition.name, selection: { codex: definition.codex, models_required: definition.modelSelection } }));
|
|
24
|
+
}
|
package/src/provider-runtime.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
|
+
import { providerDescriptors } from "./provider-descriptors.mjs";
|
|
2
3
|
import { autoReviewPreference, writeAutoReviewModel } from "./user-settings.mjs";
|
|
3
4
|
import { autoReviewReasoningEfforts, DEFAULT_CODEX_AUTO_REVIEW_MODEL, responsesModelIdsFromCopilotModels } from "./models.mjs";
|
|
4
5
|
import { publicModelCatalog } from "./provider-metadata.mjs";
|
|
@@ -201,34 +202,21 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
201
202
|
},
|
|
202
203
|
selection: () => selection,
|
|
203
204
|
dashboardProviders() {
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
models: { count: githubRegistry?.models?.data?.length ?? null, source: githubRegistry?.source || "unknown" },
|
|
209
|
-
clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "github", state: githubClientConfigured ? "configured" : "unknown" }] },
|
|
210
|
-
{ id: "m365", name: "Microsoft 365", generation: m365 ? dashboardGeneration(m365) : 0, enabled, state: ms.state, reason: ms.reason, network_diagnostic: ms.network_diagnostic,
|
|
211
|
-
auth: { state: ms.token_cached ? "authorized" : !enabled ? "disabled" : ms.reason ? "unavailable" : "unknown",
|
|
212
|
-
account: ms.account?.login || "", token_cached: ms.token_cached === true,
|
|
213
|
-
tenant: ms.account?.tenant || "", selection_source: ms.account?.selection_source || null,
|
|
214
|
-
expires_in_ms: ms.token_expires_in_ms ?? null, checked_at: ms.token_checked_at || null },
|
|
215
|
-
models: { count: ms.models?.total ?? null, source: ms.models?.source || "unavailable", checked_at: ms.models?.refreshed_at || null },
|
|
216
|
-
clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "m365", state: selection.codex === "m365" ? ms.state : "standby" },
|
|
217
|
-
...[["code", "Claude Code"], ["app", "Claude App"]].map(([id, name]) => ({ id: `claude_${id}`, name,
|
|
218
|
-
selected: enabled, state: clientLifecycle.snapshot().clients[id], gateway: gateway ? "running" : "unavailable", reason: claudeReason,
|
|
219
|
-
last_request_at: lastClients[`claude_${id}`] || null }))],
|
|
220
|
-
requests: ms.claude.requests, request_scope: "Claude Messages" },
|
|
221
|
-
];
|
|
222
|
-
return providerRegistry.list().map(definition => ({ ...projections.find(source => source.id === definition.id),
|
|
223
|
-
id: definition.id, name: definition.name, selection: { codex: definition.codex, models_required: definition.modelSelection } }));
|
|
205
|
+
return providerDescriptors({ state: snapshot(), githubRuntime: githubClient.runtimeStatus?.() || {}, githubRegistry,
|
|
206
|
+
githubClientConfigured, githubGeneration: dashboardGeneration(github), m365Generation: m365 ? dashboardGeneration(m365) : 0,
|
|
207
|
+
claudeClients: clientLifecycle.snapshot().clients, claudeReason, gatewayRunning: Boolean(gateway), lastClients,
|
|
208
|
+
definitions: providerRegistry.list() });
|
|
224
209
|
},
|
|
225
210
|
async dashboardCatalog({ provider = selection.codex } = {}) {
|
|
226
211
|
if (provider === "github") return null;
|
|
227
212
|
if (provider !== "m365") throw Object.assign(new Error("Unknown provider"), { statusCode: 400 });
|
|
228
213
|
if (!enabled || !["darwin", "win32"].includes(platform)) throw unavailable(!enabled ? "m365_disabled" : "m365_unsupported");
|
|
229
214
|
if (!m365) throw unavailable(reason || "m365_not_ready");
|
|
230
|
-
|
|
231
|
-
|
|
215
|
+
const source = m365;
|
|
216
|
+
await source.refresh();
|
|
217
|
+
if (closed || !enabled || source !== m365 || changingAccount) throw unavailable("m365_refresh_cancelled");
|
|
218
|
+
reason = null;
|
|
219
|
+
const eligible = new Set([...source.models("gpt"), ...source.models("claude")]);
|
|
232
220
|
return { source: "catalog", checkedAt: m365.snapshot().models.refreshed_at, upstreamHost: "Microsoft 365",
|
|
233
221
|
advertised: m365.catalog().length, models: publicModelCatalog(m365.catalog(), {
|
|
234
222
|
selectable: model => eligible.has(model),
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// The server body is inspected once. Only fixed causes and bounded IDs survive.
|
|
2
|
+
const causes = Object.freeze({
|
|
3
|
+
sign_in_rejected: "Microsoft 365 rejected the sign-in. Check account access.",
|
|
4
|
+
entra_access_disabled: "Copilot CLI Entra access is not enabled for this account.",
|
|
5
|
+
access_denied: "Microsoft 365 denied access to the model list.",
|
|
6
|
+
rate_limited: "Microsoft 365 limited model-list checks. Try again later.",
|
|
7
|
+
service_unavailable: "Microsoft 365 could not serve the model list.",
|
|
8
|
+
catalog_rejected: "Microsoft 365 rejected the model-list request.",
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
const date = value => typeof value === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(value)
|
|
12
|
+
&& Number.isFinite(Date.parse(value)) ? value : null;
|
|
13
|
+
|
|
14
|
+
export function m365CatalogDiagnostic(value) {
|
|
15
|
+
if (!value || value.stage !== "catalog" || !Object.hasOwn(causes, value.cause_code)
|
|
16
|
+
|| !Number.isInteger(value.http_status) || value.http_status < 400 || value.http_status > 599) return null;
|
|
17
|
+
return { stage: "catalog", cause_code: value.cause_code, http_status: value.http_status,
|
|
18
|
+
checked_at: date(value.checked_at), last_success_at: date(value.last_success_at),
|
|
19
|
+
request_id: typeof value.request_id === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(value.request_id)
|
|
20
|
+
&& !/^(?:github_pat_|gh[pousr]_|sk-|eyJ)/.test(value.request_id) ? value.request_id : null };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function m365CatalogMessage(value) {
|
|
24
|
+
const diagnostic = m365CatalogDiagnostic(value);
|
|
25
|
+
return diagnostic ? causes[diagnostic.cause_code] : null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function catalogFailure(response, body, { checkedAt, lastSuccessAt } = {}) {
|
|
29
|
+
let message;
|
|
30
|
+
try { const value = JSON.parse(body);message = value?.error?.message ?? value?.message; } catch { /* Unrecognized bodies get the HTTP category only. */ }
|
|
31
|
+
const code = response.status;
|
|
32
|
+
const cause_code = code === 401 ? "sign_in_rejected"
|
|
33
|
+
: code === 403 ? typeof message === "string" && /^Copilot CLI Entra access is not enabled for this user\.?$/i.test(message.trim())
|
|
34
|
+
? "entra_access_disabled" : "access_denied"
|
|
35
|
+
: code === 429 ? "rate_limited" : code >= 500 ? "service_unavailable" : "catalog_rejected";
|
|
36
|
+
return m365CatalogDiagnostic({ stage: "catalog", cause_code, http_status: code, checked_at: checkedAt,
|
|
37
|
+
last_success_at: lastSuccessAt, request_id: response.headers.get("request-id") || response.headers.get("x-ms-request-id") });
|
|
38
|
+
}
|
package/src/providers/m365.mjs
CHANGED
|
@@ -16,6 +16,7 @@ import { resolveClaudeModel } from "../claude-models.mjs";
|
|
|
16
16
|
import { modelReasoningEfforts } from "../provider-metadata.mjs";
|
|
17
17
|
import { limitM365CacheTtl } from "./m365-messages-policy.mjs";
|
|
18
18
|
import { createM365ConversationGuard } from "./m365-conversation-accounts.mjs";
|
|
19
|
+
import { catalogFailure, m365CatalogDiagnostic } from "./m365-catalog-diagnostic.mjs";
|
|
19
20
|
import { m365NetworkDiagnostic } from "./m365-network-diagnostic.mjs";
|
|
20
21
|
|
|
21
22
|
export const M365_API_BASE = "https://df.loki.delve.office.com/api/v1/llmapi";
|
|
@@ -75,7 +76,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
75
76
|
const guardConversation = createM365ConversationGuard({ home });
|
|
76
77
|
let catalog = null, account = null, catalogAt = 0, state = "idle", reason = null, flight = null, controller = null, generation = 0;
|
|
77
78
|
let network = null, networkFlight = null, cacheTtlAdjustments = 0;
|
|
78
|
-
let networkDiagnostic = null;
|
|
79
|
+
let networkDiagnostic = null, catalogDiagnostic = null;
|
|
79
80
|
const registry = { models: null, source: "unavailable", cacheState: "none", cacheSavedAtMs: null,
|
|
80
81
|
refreshInFlight: false, generation: 0, lastError: null, lastErrorAtMs: null };
|
|
81
82
|
const profile = () => account ? `m365:${m365AccountKey(account)}` : "m365:unavailable";
|
|
@@ -146,20 +147,23 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
146
147
|
const credential = await auth.getToken({ signal });
|
|
147
148
|
const response = await request("/models", null, { signal });
|
|
148
149
|
const raw = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES, label: "M365 model catalog", signal });
|
|
149
|
-
if (!response.ok) throw m365Error(`m365_catalog_http_${response.status}`)
|
|
150
|
+
if (!response.ok) throw Object.assign(m365Error(`m365_catalog_http_${response.status}`), {
|
|
151
|
+
catalog_diagnostic: catalogFailure(response, raw, { checkedAt: new Date(now()).toISOString(),
|
|
152
|
+
lastSuccessAt: catalogAt ? new Date(catalogAt).toISOString() : null }) });
|
|
150
153
|
let value;try { value = m365Catalog(JSON.parse(raw)); } catch { throw m365Error("m365_catalog_invalid"); }
|
|
151
154
|
if (current !== generation || signal.aborted) throw m365Error("m365_refresh_cancelled");
|
|
152
155
|
const savedAt = now();
|
|
153
156
|
const nextAccount = { ...credential.account, ...(account?.history_isolation ? { history_isolation: true } : {}) };
|
|
154
157
|
if (persist) writeM365Binding(nextAccount, { account_key: m365AccountKey(nextAccount), saved_at: savedAt, models: value }, { home, expectedAccount: account });
|
|
155
158
|
account = nextAccount;
|
|
156
|
-
applyCatalog(value, "live", savedAt);state = "ready";reason = null;registry.lastError = null;registry.lastErrorAtMs = null;
|
|
159
|
+
applyCatalog(value, "live", savedAt);catalogDiagnostic = null;state = "ready";reason = null;registry.lastError = null;registry.lastErrorAtMs = null;
|
|
157
160
|
try { await onCatalog(value); } catch { log("warn", "M365 models are ready; optional client configuration could not be updated"); }
|
|
158
161
|
return value;
|
|
159
162
|
})().catch(error => {
|
|
160
163
|
if (current === generation) {
|
|
161
164
|
state = "unavailable";reason = /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : "m365_unavailable";
|
|
162
165
|
networkDiagnostic = m365NetworkDiagnostic(error.network_diagnostic);
|
|
166
|
+
catalogDiagnostic = m365CatalogDiagnostic(error.catalog_diagnostic);
|
|
163
167
|
registry.lastError = reason;registry.lastErrorAtMs = now();
|
|
164
168
|
}
|
|
165
169
|
throw error;
|
|
@@ -254,6 +258,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
254
258
|
snapshot: () => ({ ...auth.snapshot(), state, reason: reason || auth.snapshot().reason, account: account ? { login: account.login, tenant: account.tenant, selection_source: account.selection_source || "legacy" } : null,
|
|
255
259
|
network: network?.snapshot() || null,
|
|
256
260
|
network_diagnostic: networkDiagnostic ? { ...networkDiagnostic } : null,
|
|
261
|
+
catalog_diagnostic: m365CatalogDiagnostic(catalogDiagnostic),
|
|
257
262
|
cache_ttl_adjustments: cacheTtlAdjustments,
|
|
258
263
|
models: { total: catalog?.data.length || 0, claude: m365Models(catalog, "claude").length, gpt: m365Models(catalog, "gpt").length,
|
|
259
264
|
source: registry.source, refreshed_at: catalogAt ? new Date(catalogAt).toISOString() : null }, refresh_in_flight: Boolean(flight) }),
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const APPLICATIONS = new Set(["codex_app", "codex_cli", "claude_app", "claude_code", "claude", "api"]);
|
|
2
|
+
const DECLARED = new Map([["codex-app", "codex_app"], ["codex-cli", "codex_cli"], ["claude-app", "claude_app"], ["claude-code", "claude_code"]]);
|
|
3
|
+
const ORIGINATORS = new Map([["codex_desktop", "codex_app"], ["codex_app", "codex_app"], ["codex_cli_rs", "codex_cli"]]);
|
|
4
|
+
|
|
5
|
+
export function requestApplication(headers = {}, fallback = "api") {
|
|
6
|
+
const declared = DECLARED.get(headers?.["x-ccdx-client"]);
|
|
7
|
+
if (declared) return declared;
|
|
8
|
+
// These are client-reported presentation hints, never routing or auth evidence.
|
|
9
|
+
const originator = ORIGINATORS.get(headers?.originator);
|
|
10
|
+
return originator || (APPLICATIONS.has(fallback) ? fallback : "api");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function applicationLabel(value) {
|
|
14
|
+
return APPLICATIONS.has(value) ? value : "api";
|
|
15
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { performance } from "node:perf_hooks";
|
|
2
2
|
import { currentRequestContext } from "./request-context.mjs";
|
|
3
3
|
import { isProviderId } from "./provider-metadata.mjs";
|
|
4
|
+
import { applicationLabel } from "./request-application.mjs";
|
|
4
5
|
|
|
5
6
|
const PERFORMANCE_ROUTES = Object.freeze(["responses", "responses_compact"]);
|
|
6
7
|
const PREPARATION_STAGES = Object.freeze(["admission", "body", "history", "images", "serialization"]);
|
|
@@ -12,6 +13,7 @@ const TERMINAL_ORIGINS = new Set([
|
|
|
12
13
|
]);
|
|
13
14
|
const MAX_MODEL_OUTCOME_LABELS = 32;
|
|
14
15
|
const MAX_RECENT_REQUESTS = 20;
|
|
16
|
+
const MAX_ACTIVE_REQUESTS = 64;
|
|
15
17
|
const MAX_PROVIDER_LABELS = 16;
|
|
16
18
|
const PREPARATION_EDGES_MS = Object.freeze([1, 2, 5, 10, 20, 50, 100, 250, 500, 1_000, 5_000, 30_000, 120_000]);
|
|
17
19
|
const TTFT_EDGES_MS = Object.freeze([
|
|
@@ -119,11 +121,24 @@ function histogramSnapshot(histogram, unit) {
|
|
|
119
121
|
return bucket;
|
|
120
122
|
});
|
|
121
123
|
buckets.push({ lower, upper: null, count: histogram.counts.at(-1) });
|
|
124
|
+
const percentile = fraction => {
|
|
125
|
+
if (!histogram.samples) return null;
|
|
126
|
+
const rank = Math.ceil(histogram.samples * fraction);
|
|
127
|
+
let count = 0;
|
|
128
|
+
for (const bucket of buckets) {
|
|
129
|
+
count += bucket.count;
|
|
130
|
+
if (count >= rank) return Math.min(bucket.upper ?? histogram.max, histogram.max);
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
};
|
|
122
134
|
return {
|
|
123
135
|
unit,
|
|
124
136
|
samples: histogram.samples,
|
|
125
137
|
avg: histogram.samples > 0 ? Number((histogram.total / histogram.samples).toFixed(1)) : 0,
|
|
126
138
|
max: histogram.max,
|
|
139
|
+
p50: percentile(0.5),
|
|
140
|
+
p95: percentile(0.95),
|
|
141
|
+
percentiles_estimated: true,
|
|
127
142
|
buckets,
|
|
128
143
|
};
|
|
129
144
|
}
|
|
@@ -199,12 +214,18 @@ function routeSnapshot(route) {
|
|
|
199
214
|
export function createStreamPerformanceMetrics({ now = () => performance.now(), wallNow = () => new Date().toISOString(), routeNames = PERFORMANCE_ROUTES } = {}) {
|
|
200
215
|
const routes = Object.fromEntries(routeNames.map((name) => [name, createRoutePerformance()]));
|
|
201
216
|
const recentRequests = [];
|
|
217
|
+
const activeRequests = new Map();
|
|
218
|
+
let activeTotal = 0, activeSequence = 0;
|
|
202
219
|
|
|
203
220
|
return {
|
|
204
|
-
begin(routeName, { requestId } = {}) {
|
|
221
|
+
begin(routeName, { requestId, application } = {}) {
|
|
205
222
|
const route = routes[routeName];
|
|
206
223
|
if (!route) return null;
|
|
207
224
|
const requestStartedAt = now();
|
|
225
|
+
const activeId = ++activeSequence;
|
|
226
|
+
const safeRequestId = typeof requestId === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(requestId) ? requestId : null;
|
|
227
|
+
const client = applicationLabel(application);
|
|
228
|
+
activeTotal++;
|
|
208
229
|
let upstreamStartedAt = null;
|
|
209
230
|
let firstOutputAt = null;
|
|
210
231
|
let firstOutputSource = null;
|
|
@@ -229,6 +250,12 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
229
250
|
let terminalAt = null;
|
|
230
251
|
const context = { payload_bytes: null, images: null, input_tokens: null, context_window_tokens: null };
|
|
231
252
|
const elapsed = (time) => time === null ? null : Number(Math.max(0, time - requestStartedAt).toFixed(1));
|
|
253
|
+
if (activeRequests.size < MAX_ACTIVE_REQUESTS) activeRequests.set(activeId, () => ({
|
|
254
|
+
request_id: safeRequestId, application: client, route: routeName, provider, model, phase,
|
|
255
|
+
started_at: at, elapsed_ms: elapsed(now()), first_output_ms: elapsed(firstOutputAt),
|
|
256
|
+
upstream_attempts: attempts, terminal_outcome: terminalOutcome,
|
|
257
|
+
attempts: attemptTimings.map(attempt => ({ ...attempt })),
|
|
258
|
+
}));
|
|
232
259
|
const assignProvider = value => {
|
|
233
260
|
if (finished || sourceStats || !isProviderId(value)) return;
|
|
234
261
|
provider = value;
|
|
@@ -322,6 +349,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
322
349
|
if (finished) return;
|
|
323
350
|
if (!sourceStats) assignProvider("unknown");
|
|
324
351
|
finished = true;
|
|
352
|
+
activeTotal--;activeRequests.delete(activeId);
|
|
325
353
|
failed ||= finishFailed;
|
|
326
354
|
const outcome = terminalOutcome || (aborted ? "cancelled" : "unknown");
|
|
327
355
|
const emptyStreamCompletion = outcome === "completed" && upstreamStartedAt !== null
|
|
@@ -347,7 +375,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
347
375
|
const finishedAt = now();
|
|
348
376
|
// Only scalar, allowlisted metadata survives the request; never retain payloads.
|
|
349
377
|
recentRequests.push({
|
|
350
|
-
request_id:
|
|
378
|
+
request_id: safeRequestId, application: client,
|
|
351
379
|
at, route: routeName, model, outcome, origin, phase,
|
|
352
380
|
...(provider ? { provider } : {}),
|
|
353
381
|
empty_stream_completion: emptyStreamCompletion,
|
|
@@ -394,6 +422,9 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
394
422
|
snapshot() {
|
|
395
423
|
return {
|
|
396
424
|
by_route: Object.fromEntries(routeNames.map((name) => [name, routeSnapshot(routes[name])])),
|
|
425
|
+
active_requests: [...activeRequests.values()].map(snapshot => snapshot()),
|
|
426
|
+
active_total: activeTotal,
|
|
427
|
+
active_omitted: Math.max(0, activeTotal - activeRequests.size),
|
|
397
428
|
recent_requests: recentRequests.map((entry) => ({ ...entry, attempts: entry.attempts.map(attempt => ({ ...attempt })), context: { ...entry.context }, timings_ms: { ...entry.timings_ms } })),
|
|
398
429
|
};
|
|
399
430
|
},
|