codex-copilot-dx 1.2.22 → 1.2.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/docs/ARCHITECTURE.md +24 -0
- package/docs/REFERENCE.md +43 -5
- package/package.json +1 -1
- package/src/adapter.mjs +6 -4
- package/src/api-catalog-refresh.mjs +5 -2
- package/src/claude-gateway.mjs +19 -3
- package/src/cli-status.mjs +2 -2
- package/src/connection-runtime.mjs +9 -1
- package/src/conversation-source-guard.mjs +3 -1
- package/src/dashboard/console.js +6 -1
- package/src/dashboard/flow.js +45 -26
- package/src/dashboard/index.html +2 -0
- package/src/dashboard/language.js +23 -0
- package/src/dashboard/status.js +29 -8
- package/src/dashboard/ui.css +2 -0
- package/src/providers/api-token-count.mjs +61 -0
- package/src/providers/api.mjs +11 -3
- package/src/request-context.mjs +8 -0
- package/src/response-failures.mjs +25 -5
- package/src/responses-handler.mjs +3 -0
- package/src/stream-performance.mjs +3 -1
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ npm install -g codex-copilot-dx@latest
|
|
|
11
11
|
ccdx
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.
|
|
14
|
+
No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.23/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.23/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
|
|
15
15
|
|
|
16
16
|
CCDX reuses a compatible local credential or starts GitHub Device Flow, listens on `127.0.0.1:2026`, configures Codex, and opens the App. Interactive desktop starts also open the local WebUI once; use `ccdx --no-browser` or disable this in WebUI settings. No client binary patch is needed. On Windows, open the App manually unless native prediction setup is enabled. In restricted Windows PowerShell, use `npm.cmd` to install and `ccdx.cmd` for the first launch, or run `ccdx.cmd doctor --fix`. Startup, updates and explicit repair remove only CCDX's exact npm-generated `.ps1` launchers so later calls can use `ccdx`. The npm package adds no install hook or policy change; custom launchers are preserved. npm's own script is untouched. The configured `dummy` API key is a placeholder, not a credential.
|
|
17
17
|
|
|
@@ -52,11 +52,11 @@ Requests shows live app/source/model flow above existing summaries and finished
|
|
|
52
52
|
|
|
53
53
|
## Add your own API
|
|
54
54
|
|
|
55
|
-
Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. GitHub-only Codex selections retain native OpenAI mode and readable model names. A request stays on its selected deployment; there is no automatic cross-source retry or model replacement. Reopen clients after configuration changes and start a new conversation after source/key changes. Stop management before normal `ccdx` startup for the live terminal.
|
|
55
|
+
Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. GitHub-only Codex selections retain native OpenAI mode and readable model names. Token counting is separate from message generation. For manual APIs, an observed count-endpoint 404 is remembered for one minute per model/API-header scope; CCDX returns a clear 404 without inventing a token count. Identical concurrent count requests share bounded upstream work. A request stays on its selected deployment; there is no automatic cross-source retry or model replacement. Reopen clients after configuration changes and start a new conversation after source/key changes. Stop management before normal `ccdx` startup for the live terminal.
|
|
56
56
|
|
|
57
57
|
Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving reads model metadata automatically, without inference. Startup and the existing model refresh cycle also refresh enabled APIs when the 30-minute cache expires; failed reads retain saved configuration. Closed sources can be restored on Model sources; closed apps remain reachable for restoration on their app pages. Pinned streams finish on their original source. The version-two graph preserves old single-source visibility and saves a byte-for-byte v1 backup before migration. User and managed client settings remain protected.
|
|
58
58
|
|
|
59
|
-
Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.
|
|
59
|
+
Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.23 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.23.md) cover request attribution, bounded token-count compatibility and lower-cost flow rendering while retaining native GitHub sign-in/model protections.
|
|
60
60
|
|
|
61
61
|
## Microsoft 365 access
|
|
62
62
|
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -768,3 +768,27 @@ existing cancellation-aware single-flight for transport initialization: one
|
|
|
768
768
|
waiter cannot abort another, while the last cancellation or provider closure
|
|
769
769
|
stops the shared setup. Existing native stream validation, byte admission,
|
|
770
770
|
connection reuse, bounded metrics/logging and pinned source semantics remain.
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
## Request evidence and optional counting
|
|
774
|
+
|
|
775
|
+
The existing AsyncLocalStorage request context owns safe requested model and
|
|
776
|
+
client evidence before model resolution. Claude keeps the outer HTTP context,
|
|
777
|
+
while its generation metrics stay separate from count operations. Selected
|
|
778
|
+
source/model, logical upstream calls and fixed resolution reasons reach HTTP
|
|
779
|
+
diagnostics; no alternate route is chosen to improve a diagnostic result.
|
|
780
|
+
|
|
781
|
+
`providers/api-token-count.mjs` is owned by one immutable manual-API
|
|
782
|
+
configuration. It joins bounded identical count operations with independent
|
|
783
|
+
waiter cancellation and keeps only bounded, short-lived 404 observations.
|
|
784
|
+
It does not implement a general circuit breaker, protocol translation,
|
|
785
|
+
inference fallback or tokenizer. Counts have their own diagnostics category;
|
|
786
|
+
generation failure totals do not include this auxiliary capability.
|
|
787
|
+
|
|
788
|
+
Flow rendering caches geometry until observed element size, topology, model
|
|
789
|
+
labels or language change. Phase-only updates retain SVG path/circle nodes.
|
|
790
|
+
Hidden pages stop the two-second status timer and refresh on visibility return;
|
|
791
|
+
foreground freshness and the existing CSS motion remain unchanged. Catalog
|
|
792
|
+
failure backoff is source-revision scoped and never holds the configuration
|
|
793
|
+
transaction during network work. Existing body serialization ownership is
|
|
794
|
+
retained: the ordinary manual Responses path serializes its final body once.
|
package/docs/REFERENCE.md
CHANGED
|
@@ -1302,7 +1302,7 @@ Unknown support prevents an explicitly requested exception from starting.
|
|
|
1302
1302
|
For an older updater that still requires Git, install the Release tarball directly:
|
|
1303
1303
|
|
|
1304
1304
|
```sh
|
|
1305
|
-
npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.
|
|
1305
|
+
npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.23/codex-copilot-dx-1.2.23.tgz
|
|
1306
1306
|
# Windows PowerShell: use npm.cmd instead of npm.
|
|
1307
1307
|
```
|
|
1308
1308
|
|
|
@@ -1693,11 +1693,14 @@ The protected `/_ccdx/ui/account` and `/_ccdx/ui/checks` APIs require loopback,
|
|
|
1693
1693
|
## HTTP error diagnostics
|
|
1694
1694
|
|
|
1695
1695
|
`http_errors.recent` keeps its 20-record rolling view. Independent
|
|
1696
|
-
`actionable_recent` (20
|
|
1697
|
-
|
|
1698
|
-
|
|
1696
|
+
`actionable_recent` (20 generation/other failures and actionable count errors),
|
|
1697
|
+
`capability_recent` (20 token-count errors), `route_recent` (eight path errors)
|
|
1698
|
+
and `protocol_recent` (eight image-MCP HTTP 405 records) prevent route/method noise from erasing inference
|
|
1699
|
+
evidence. `by_category` counts inference, capability, protocol, route and other HTTP failures;
|
|
1699
1700
|
classification does not discard errors, grant access or retry requests.
|
|
1700
|
-
The WebUI
|
|
1701
|
+
The WebUI defaults to reply issues and provides separate capability and connection/path views. Repeated capability/path notices are grouped within the bounded retained records, with their occurrence count and latest request details; raw HTTP counters remain visible. A count-endpoint 404 is not a failed generation. Count authentication, rate-limit and server failures remain actionable.
|
|
1702
|
+
|
|
1703
|
+
Before model resolution, safe requested model IDs and the client hint are retained even for local rejection. Known binding failures include a specific reason: model not selected, ambiguous name, unavailable catalog entry or disabled access. These diagnostics never authorize a model or replace it with a default. Claude records propagate the actual model/source and distinguish a cached capability result from an upstream HTTP failure. Upstream attempts count logical calls; shared counts are marked `shared_upstream`, and cached 404s report zero calls. No prompt or key is retained.
|
|
1701
1704
|
|
|
1702
1705
|
New records retain safe error code/type/parameter paths, method, an allowlisted
|
|
1703
1706
|
endpoint without a query, and upstream attempt count. Requested/served model
|
|
@@ -2046,3 +2049,38 @@ inference remains separate. Protected JSON/account/settings routes stay
|
|
|
2046
2049
|
`CCDX_SUPERVISED_SERVICE` is an internal inherited worker marker. It is used only
|
|
2047
2050
|
with a private parent IPC channel; do not set it as a user preference. It grants
|
|
2048
2051
|
no network action and is not a replacement for the saved nightly-update opt-in.
|
|
2052
|
+
|
|
2053
|
+
|
|
2054
|
+
### Manual API token counting
|
|
2055
|
+
|
|
2056
|
+
Messages support does not establish support for `POST /v1/messages/count_tokens`.
|
|
2057
|
+
CCDX forwards the configured Messages endpoint plus `/count_tokens`. A manual
|
|
2058
|
+
API's observed HTTP 404 is remembered in memory for 60 seconds, separately for
|
|
2059
|
+
each model and Anthropic version/beta-header scope. This is an observed endpoint
|
|
2060
|
+
failure, not a declaration that the model source is down. Cached and initial
|
|
2061
|
+
results return HTTP 404 with `ccdx_api_count_tokens_unavailable`; no estimated
|
|
2062
|
+
or synthetic count is returned. Changing the source configuration/key creates
|
|
2063
|
+
a new scope. Other statuses, including 401/403/405/429/5xx, are not cached by
|
|
2064
|
+
this compatibility mechanism; status and safe Retry-After metadata survive.
|
|
2065
|
+
|
|
2066
|
+
Identical concurrent count requests share one bounded upstream operation.
|
|
2067
|
+
Each caller cancels independently; the last cancelled waiter aborts shared
|
|
2068
|
+
work. Joining is limited to bodies up to 1 MiB, 16 shared operations and 4 MiB
|
|
2069
|
+
of shared request text. Larger/overflow requests use their normal admitted
|
|
2070
|
+
path. Count responses are capped at 64 KiB. At most 128 recent unavailable
|
|
2071
|
+
scopes are retained. Successful results and request bodies are not retained
|
|
2072
|
+
after the operation. Counts neither invoke generation nor fail over to another
|
|
2073
|
+
source. This does not supply a missing tokenizer or guarantee every Claude App
|
|
2074
|
+
context-management feature on a third-party model.
|
|
2075
|
+
|
|
2076
|
+
Background manual-API catalog failures back off for 1, 5, 30 and then 120
|
|
2077
|
+
minutes; successful publication resets the sequence. Explicit refresh retains
|
|
2078
|
+
the existing one-minute minimum interval rather than the longer background
|
|
2079
|
+
backoff. A valid upstream Retry-After also applies, bounded to 24 hours. These
|
|
2080
|
+
are read eligibility gates, not added background retry timers. Revision changes
|
|
2081
|
+
invalidate prior eligibility and obsolete results never publish.
|
|
2082
|
+
|
|
2083
|
+
Claude Code's validated `x-claude-code-agent-id` separates a child task's local
|
|
2084
|
+
source guard from its parent's guard when a session is identified. Parent keys
|
|
2085
|
+
without that header remain unchanged. This header is correlation only: model
|
|
2086
|
+
access and the company's account/history checks remain authoritative.
|
package/package.json
CHANGED
package/src/adapter.mjs
CHANGED
|
@@ -420,12 +420,13 @@ export function createAdapterHandler(options = {}) {
|
|
|
420
420
|
if (requestFinished) return;
|
|
421
421
|
requestFinished = true;
|
|
422
422
|
if (trackRequest && statusCode >= 400) {
|
|
423
|
-
try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model,
|
|
423
|
+
try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model || context?.requestedModel,
|
|
424
424
|
method: ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"].includes(req.method) ? req.method : "OTHER",
|
|
425
425
|
target: ["/v1/responses", "/v1/responses/compact", "/anthropic/v1/messages", "/anthropic/v1/messages/count_tokens", "/anthropic/v1/models", "/mcp/image", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname) ? pathname : "unrecognized_path",
|
|
426
|
-
request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.(),
|
|
426
|
+
request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.() ?? context?.upstreamAttempts,
|
|
427
427
|
attempt_timings: streamPerformance?.attemptTimings?.(),
|
|
428
|
-
requested_model: context?.requestedModel, provider: context?.provider,
|
|
428
|
+
requested_model: context?.requestedModel, provider: context?.provider, application: context?.application || requestApplication(req.headers),
|
|
429
|
+
capability_cached: context?.countObservation?.cached, shared_upstream: context?.countObservation?.shared,
|
|
429
430
|
})); } catch {}
|
|
430
431
|
}
|
|
431
432
|
try { complete({ statusCode, aborted }); } catch {}
|
|
@@ -466,13 +467,14 @@ export function createAdapterHandler(options = {}) {
|
|
|
466
467
|
showRequestId: options.showRequestId === true,
|
|
467
468
|
includeHttpErrorDetails: options.includeHttpErrorDetails === true || process.env.CCDX_HTTP_ERROR_DETAILS === "1",
|
|
468
469
|
streamPerformance,
|
|
470
|
+
upstreamAttempts: 0,
|
|
469
471
|
provider: undefined,
|
|
470
472
|
finishProvider: undefined,
|
|
471
473
|
historyNamespace: undefined,
|
|
472
474
|
historyTransferNamespace: undefined,
|
|
473
475
|
onHistoryStored: undefined,
|
|
474
476
|
clientHeaders: undefined,
|
|
475
|
-
onHttpError: evidence => { httpEvidence = evidence; },
|
|
477
|
+
onHttpError: evidence => { httpEvidence = { ...httpEvidence, ...evidence }; },
|
|
476
478
|
};
|
|
477
479
|
const result = runWithRequestContext(context, () => dispatchRequest(req, res, pathname));
|
|
478
480
|
if (result && typeof result.then === "function") {
|
|
@@ -21,7 +21,8 @@ export function createApiCatalogRefresh({ config, source, track, revision, commi
|
|
|
21
21
|
if (old?.revision === version && !old.controller.signal.aborted) return old.promise;
|
|
22
22
|
if (old) cancel(id);
|
|
23
23
|
const cached = reads.get(id), age = cached ? now() - cached.at : Infinity;
|
|
24
|
-
|
|
24
|
+
const retryDelay = cached?.error ? [60000, 5 * 60000, 30 * 60000, 2 * 60 * 60000][Math.min((cached.failures || 1) - 1, 3)] : 0;
|
|
25
|
+
if (cached?.revision === version && age >= 0 && age < Math.max(cached.retryAfterMs || 0, force ? 60000 : cached.error ? retryDelay : 30 * 60000)) {
|
|
25
26
|
if (cached.error) throw cached.error;
|
|
26
27
|
await commit(id, cached.models, version, new Date(cached.at).toISOString(), () => current(id, version));
|
|
27
28
|
onState(id, { state: "ready", checked_at: new Date(cached.at).toISOString() });return cached.models;
|
|
@@ -48,7 +49,9 @@ export function createApiCatalogRefresh({ config, source, track, revision, commi
|
|
|
48
49
|
const code = /^ccdx_[a-z0-9_]+$/.test(error.code || "") ? error.code : "ccdx_api_catalog_unavailable";
|
|
49
50
|
const failure = accessError(code, [401, 403, 409].includes(error.statusCode) ? error.statusCode : 502);
|
|
50
51
|
if (active()) {
|
|
51
|
-
reads.set(id, { revision: version, at: now(), error: failure
|
|
52
|
+
reads.set(id, { revision: version, at: now(), error: failure,
|
|
53
|
+
retryAfterMs: Number.isFinite(error.retryAfterMs) ? Math.max(0, Math.min(error.retryAfterMs, 86400000)) : 0,
|
|
54
|
+
failures: cached?.revision === version ? Math.min((cached.failures || 0) + 1, 4) : 1 });
|
|
52
55
|
onState(id, { state: "stale", code, checked_at: new Date(now()).toISOString() });
|
|
53
56
|
}
|
|
54
57
|
throw failure;
|
package/src/claude-gateway.mjs
CHANGED
|
@@ -7,7 +7,8 @@ import { createRequestAdmission } from "./request-admission.mjs";
|
|
|
7
7
|
import { loadRuntimeConfig } from "./runtime-config.mjs";
|
|
8
8
|
import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
|
|
9
9
|
import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
|
|
10
|
-
import { runWithRequestContext, currentRequestContext } from "./request-context.mjs";
|
|
10
|
+
import { runWithRequestContext, currentRequestContext, observeRequestedModel } from "./request-context.mjs";
|
|
11
|
+
import { upstreamErrorEvidence } from "./response-failures.mjs";
|
|
11
12
|
import { createStreamPerformanceMetrics, isMessagesOutputDelta } from "./stream-performance.mjs";
|
|
12
13
|
import { buildMessagesUsageRecord, recordUsage } from "./usage-store.mjs";
|
|
13
14
|
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
@@ -17,6 +18,8 @@ import { requestApplication } from "./request-application.mjs";
|
|
|
17
18
|
|
|
18
19
|
function send(res, code, value) {
|
|
19
20
|
if (res.destroyed || res.writableEnded) return;
|
|
21
|
+
const context = currentRequestContext();
|
|
22
|
+
if (code >= 400) context?.onHttpError?.({ code: value?.error?.code, origin: context.errorOrigin || "client_validation" });
|
|
20
23
|
res.writeHead(code, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(value));
|
|
21
24
|
}
|
|
22
25
|
const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
|
|
@@ -113,17 +116,21 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
113
116
|
const parent = currentRequestContext();
|
|
114
117
|
if (parent) parent.provider = provider.id;
|
|
115
118
|
const countTokens = pathname.endsWith("/count_tokens"), requestId = parent?.requestId || randomUUID();
|
|
116
|
-
const tracker = countTokens ?
|
|
119
|
+
const tracker = countTokens ? parent?.streamPerformance : performance.begin("messages", { requestId, application: requestApplication(req.headers, "claude") });
|
|
117
120
|
if (!resolveRequest) tracker?.setProvider(provider.id);
|
|
118
121
|
const abort = createRequestAbort(req, res);
|
|
119
122
|
let release = () => {}, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
|
|
120
123
|
let terminalOrigin = "client_validation", failureStatus = null;
|
|
121
124
|
if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
|
|
122
|
-
|
|
125
|
+
const context = parent || { requestId };
|
|
126
|
+
context.provider = selectedProvider.id;context.application = requestApplication(req.headers, "claude");
|
|
127
|
+
context.streamPerformance = tracker;context.route = countTokens ? "messages_count_tokens" : "messages";
|
|
128
|
+
await runWithRequestContext(context, async () => {
|
|
123
129
|
try {
|
|
124
130
|
release = await acquireRequest(req, { signal: abort.signal });
|
|
125
131
|
abort.setTimeout(config.requestBodyTimeoutMs, "request_body_timeout");
|
|
126
132
|
let body = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: config.maxBodyBytes, maxDecodedBodyBytes: decodedLimit });
|
|
133
|
+
observeRequestedModel(body);
|
|
127
134
|
if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
|
|
128
135
|
send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
|
|
129
136
|
}
|
|
@@ -140,10 +147,15 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
140
147
|
if (desktopAliases && !configuredModel) throw Object.assign(new Error("The selected model is unavailable"), { code: "ccdx_api_model_unavailable", statusCode: 400 });
|
|
141
148
|
if (desktopAliases && configuredModel !== model) { clientModel = model;model = configuredModel;body = { ...body, model }; }
|
|
142
149
|
stats.last_model = model;
|
|
150
|
+
context.model = configuredModel || model;
|
|
143
151
|
tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
|
|
144
152
|
validateConversation?.(body, req.headers, selectedProvider);
|
|
145
153
|
terminalOrigin = "transport";
|
|
146
154
|
const upstream = await selectedProvider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
|
|
155
|
+
onCountObservation(value) {
|
|
156
|
+
context.countObservation = { ...context.countObservation, ...value };
|
|
157
|
+
if (value.upstream) { context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;tracker?.upstreamStarted(false); }
|
|
158
|
+
},
|
|
147
159
|
onUpstreamStart() { abort.setTimeout(streamed ? config.streamHandshakeTimeoutMs : config.upstreamTimeoutMs, "upstream_timeout"); } });
|
|
148
160
|
body = null;
|
|
149
161
|
terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
|
|
@@ -156,6 +168,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
156
168
|
const raw = await readBoundedResponseText(upstream, { maxBytes: upstream.ok ? config.maxUpstreamResponsesResponseBytes : MAX_UPSTREAM_ERROR_BODY_BYTES,
|
|
157
169
|
label: "Claude gateway response", signal: abort.signal });
|
|
158
170
|
let value;try { value = JSON.parse(raw); } catch {}
|
|
171
|
+
if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw),
|
|
172
|
+
origin: context.countObservation?.cached ? "capability_cache" : "upstream_http", headers: upstream.headers });
|
|
159
173
|
if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
|
|
160
174
|
model = value.model || model;responseId = value.id;usage = value.usage;stopReason = value.stop_reason;
|
|
161
175
|
sawStop = typeof stopReason === "string";outcome = stopReason === "max_tokens" ? "incomplete" : sawStop ? "completed" : "failed";
|
|
@@ -195,10 +209,12 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
195
209
|
outcome = detail.source === "cancelled" ? "cancelled" : "failed";
|
|
196
210
|
const statusCode = detail.status || (abort.reason ? abortErrorStatusCode(abort.reason) : 502);
|
|
197
211
|
failureStatus = statusCode;terminalOrigin = outcome === "cancelled" ? "client_disconnect" : statusCode < 500 && statusCode !== 429 ? "client_validation" : "transport";
|
|
212
|
+
context.errorOrigin = terminalOrigin;
|
|
198
213
|
const message = redactDiagnosticText(error.message).split(apiKey).join("[redacted]").slice(0, 240);
|
|
199
214
|
const diagnostic = error.code === "ccdx_api_network_unavailable" ? transportErrorDetails(error) : null;
|
|
200
215
|
log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}${diagnostic ? ` (${diagnostic.code}, ${diagnostic.phase})` : ""}`);
|
|
201
216
|
tracker?.setErrorOrigin(terminalOrigin);
|
|
217
|
+
context.onHttpError?.({ code: detail.code, origin: terminalOrigin });
|
|
202
218
|
if (outcome === "cancelled") return;
|
|
203
219
|
if (!res.headersSent) {
|
|
204
220
|
const value = apiError(error.code || abort.reason || "ccdx_gateway_error", message);
|
package/src/cli-status.mjs
CHANGED
|
@@ -200,9 +200,9 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
|
|
|
200
200
|
if (data.http_errors) {
|
|
201
201
|
lines.push(status("info", `HTTP failures: ${count(data.http_errors.total)} observed (separate from model terminal events)`));
|
|
202
202
|
const categories = data.http_errors.by_category;
|
|
203
|
-
if (categories) lines.push(status("info", `HTTP categories: ${count(categories.inference)}
|
|
203
|
+
if (categories) lines.push(status("info", `HTTP categories: ${count(categories.inference)} generation, ${count(categories.capability)} token counts, ${count(categories.protocol)} unsupported MCP methods, ${count(categories.route)} unmatched routes, ${count(categories.other)} other`));
|
|
204
204
|
for (const failure of (data.http_errors.actionable_recent || []).slice(-3).reverse()) {
|
|
205
|
-
lines.push(status("warn", `HTTP ${count(failure.http_status)} ${terminalCell(failure.model)} ${terminalCell(failure.code)}${failure.parameter ? ` param=${terminalCell(failure.parameter)}` : ""}; ${terminalCell(failure.origin)}; ${count(failure.upstream_attempts)} attempts`));
|
|
205
|
+
lines.push(status("warn", `HTTP ${count(failure.http_status)} ${terminalCell(failure.model)} ${terminalCell(failure.code)}${failure.reason ? ` reason=${terminalCell(failure.reason)}` : ""}${failure.parameter ? ` param=${terminalCell(failure.parameter)}` : ""}; ${terminalCell(failure.origin)}; ${count(failure.upstream_attempts)} attempts`));
|
|
206
206
|
}
|
|
207
207
|
}
|
|
208
208
|
lines.push(status("info", `Models: ${count(models.models)} total; Copilot token ${copilot.token_cached ? `cached (${duration(copilot.token_expires_in_ms)} remaining)` : "not cached"}`));
|
|
@@ -75,7 +75,15 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
75
75
|
}
|
|
76
76
|
function resolveDeployment(id, model) {
|
|
77
77
|
const value = plan(id), record = value.routes.get(model);
|
|
78
|
-
if (!record)
|
|
78
|
+
if (!record) {
|
|
79
|
+
const selected = binding(id), configured = selected.deployments || [{ source: selected.source, model: selected.model }];
|
|
80
|
+
const matches = configured.filter(item => item.model === model || deploymentModelId(item.source, item.model) === model);
|
|
81
|
+
const reason = !selected.enabled ? "ccdx_client_source_disabled" : matches.length > 1 ? "ccdx_model_ambiguous"
|
|
82
|
+
: matches.length && !permitted(id, matches[0].source) ? "ccdx_client_source_disabled"
|
|
83
|
+
: matches.length ? "ccdx_model_catalog_unavailable" : "ccdx_model_not_selected";
|
|
84
|
+
const error = accessError("ccdx_api_model_unavailable");error.jsonBody.error.reason = reason;
|
|
85
|
+
currentRequestContext()?.onHttpError?.({ code: error.code, origin: "client_validation", reason });throw error;
|
|
86
|
+
}
|
|
79
87
|
const provider = requireSource(id, record.source);
|
|
80
88
|
if (provider !== record.provider) { plans.delete(id);return resolveDeployment(id, model); }
|
|
81
89
|
return record;
|
|
@@ -22,7 +22,9 @@ export function createConversationSourceGuard(options = {}) {
|
|
|
22
22
|
const identified = typeof session === "string" && session.length > 0 && session.length <= 512 && !/[\u0000-\u001f\u007f]/.test(session);
|
|
23
23
|
const first = items.find(item => item?.role === "user"), input = identified ? `session\0${session}` : first ? `first\0${JSON.stringify(first)}` : typeof body.input === "string" ? `first\0${body.input}` : null;
|
|
24
24
|
if (!input) return;
|
|
25
|
-
const
|
|
25
|
+
const agent = headers["x-claude-code-agent-id"];
|
|
26
|
+
const child = identified && ["claude_app", "claude_code"].includes(client) && typeof agent === "string" && /^[\w-]{1,128}$/.test(agent) ? `\0agent\0${agent}` : "";
|
|
27
|
+
const key = hash(client + "\0" + input + child), owner = hash(profile);
|
|
26
28
|
if (cache?.[key] === owner) return;
|
|
27
29
|
if (cache?.[key] && (identified || hasHistory)) throw accessError("ccdx_conversation_source_changed", 409);
|
|
28
30
|
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
package/src/dashboard/console.js
CHANGED
|
@@ -289,7 +289,7 @@
|
|
|
289
289
|
// Only the small in-memory status snapshot is read at this cadence. Catalogs
|
|
290
290
|
// and retained usage keep their existing on-demand, bounded refresh policy.
|
|
291
291
|
function schedule() {
|
|
292
|
-
clearTimeout(timer);if (stopped) return;
|
|
292
|
+
clearTimeout(timer);if (stopped || document.visibilityState !== "visible" || !dashboardRefresh.automatic) return;
|
|
293
293
|
timer = setTimeout(async () => {
|
|
294
294
|
if (document.visibilityState === "visible" && dashboardRefresh.automatic) {
|
|
295
295
|
await dashboardRefresh.refresh("status", { force: true });
|
|
@@ -302,6 +302,11 @@
|
|
|
302
302
|
}, 2000);
|
|
303
303
|
}
|
|
304
304
|
window.addEventListener("hashchange", navigate);
|
|
305
|
+
document.addEventListener("visibilitychange", () => {
|
|
306
|
+
if (!stopped && document.visibilityState === "visible" && dashboardRefresh.automatic) void dashboardRefresh.refresh("status", { force: true });
|
|
307
|
+
schedule();
|
|
308
|
+
});
|
|
309
|
+
el("auto-refresh").addEventListener("click", schedule);
|
|
305
310
|
el("refresh").addEventListener("click", () => { if (settingsViews.includes(current)) void loadSettings(); });
|
|
306
311
|
window.addEventListener("pagehide", () => { stopped = true;clearTimeout(timer); });
|
|
307
312
|
window.addEventListener("pageshow", () => { stopped = false;schedule(); });
|
package/src/dashboard/flow.js
CHANGED
|
@@ -8,8 +8,9 @@
|
|
|
8
8
|
const nodes = { apps: new Map(), models: new Map() };
|
|
9
9
|
const detailRows = new Map();
|
|
10
10
|
let rows = [], total = null, omitted = 0, fresh = false, deadline = 0, expiry = null;
|
|
11
|
-
let selected = null, expanded = false, lastSignature = "", geometry = "", known = false;
|
|
11
|
+
let selected = null, expanded = false, lastSignature = "", geometry = "", wireState = "", positions = null, known = false;
|
|
12
12
|
let lastApps = [], lastModels = [];
|
|
13
|
+
const resize = new ResizeObserver(() => { positions = null;draw(); });
|
|
13
14
|
const visible = () => document.visibilityState === "visible" && !root.closest("[hidden]");
|
|
14
15
|
const integer = value => Number.isSafeInteger(value) && value >= 0;
|
|
15
16
|
const appName = id => format(`flow_app_${id}`);
|
|
@@ -47,7 +48,7 @@
|
|
|
47
48
|
function project(type, groups) {
|
|
48
49
|
const target = el(type === "apps" ? "flow-apps" : "flow-models"), cache = nodes[type], fragments = [];
|
|
49
50
|
const ids = new Set(groups.map(group => group.id));
|
|
50
|
-
for (const [id, node] of cache) if (!ids.has(id)) { node.remove();cache.delete(id); }
|
|
51
|
+
for (const [id, node] of cache) if (!ids.has(id)) { resize.unobserve?.(node);node.remove();cache.delete(id);positions = null; }
|
|
51
52
|
for (const group of groups) {
|
|
52
53
|
let node = cache.get(group.id);
|
|
53
54
|
if (!node) {
|
|
@@ -59,15 +60,16 @@
|
|
|
59
60
|
});
|
|
60
61
|
node.append(button, count, note);
|
|
61
62
|
if (type === "models") node.append(entry("span", "flow-source"));
|
|
62
|
-
cache.set(group.id, node);
|
|
63
|
+
cache.set(group.id, node);resize.observe(node);positions = null;
|
|
63
64
|
}
|
|
64
65
|
const [button, count, note] = node.children;
|
|
65
|
-
|
|
66
|
+
const title = type === "apps" ? appName(group.id) : modelName(group.model);
|
|
67
|
+
if (button.textContent !== title) { button.textContent = title;positions = null; }
|
|
66
68
|
button.setAttribute("aria-pressed", String(selected?.type === type && selected.id === group.id));
|
|
67
69
|
count.hidden = fresh && omitted === 0 && group.rows.length < 2;
|
|
68
70
|
if (fresh && (group.rows.length || total === 0)) label(count, omitted ? "flow_count_lower" : "flow_count", { count: group.rows.length.toLocaleString() });
|
|
69
71
|
else count.textContent = "—";
|
|
70
|
-
if (type === "models") node.children[3].textContent = sourceName(group.provider);
|
|
72
|
+
if (type === "models" && node.children[3].textContent !== sourceName(group.provider)) { node.children[3].textContent = sourceName(group.provider);positions = null; }
|
|
71
73
|
const output = group.rows.filter(responding).length;
|
|
72
74
|
const phase = group.rows.every(row => row.terminal_outcome) ? "flow_finishing"
|
|
73
75
|
: group.rows.every(row => row.upstream_attempts > 1) ? "flow_retrying" : "flow_waiting";
|
|
@@ -77,7 +79,7 @@
|
|
|
77
79
|
// Keep existing buttons and their focus when counts or phases change.
|
|
78
80
|
const wanted = new Set(fragments);
|
|
79
81
|
for (const node of [...target.children]) if (!wanted.has(node)) node.remove();
|
|
80
|
-
fragments.forEach((node, index) => { if (target.children[index] !== node) target.insertBefore(node, target.children[index] || null); });
|
|
82
|
+
fragments.forEach((node, index) => { if (target.children[index] !== node) { target.insertBefore(node, target.children[index] || null);positions = null; } });
|
|
81
83
|
}
|
|
82
84
|
function details() {
|
|
83
85
|
label(el("flow-active-title"), fresh ? "flow_active_count" : "flow_last_count", { count: rows.filter(related).length });
|
|
@@ -119,7 +121,7 @@
|
|
|
119
121
|
label(el("flow-more"), expanded ? "flow_fewer_models" : "flow_more_models", { count: Math.max(0, models.length - 12) });
|
|
120
122
|
project("apps", shownApps);
|
|
121
123
|
project("models", expanded ? models : models.slice(0, 12));
|
|
122
|
-
|
|
124
|
+
draw();
|
|
123
125
|
}
|
|
124
126
|
function rounded(x0, y0, x1, y1) {
|
|
125
127
|
if (Math.abs(y1 - y0) < 2) return `M${x0} ${y0}H${x1}`;
|
|
@@ -128,25 +130,42 @@
|
|
|
128
130
|
}
|
|
129
131
|
function draw() {
|
|
130
132
|
if (!visible()) return;
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
133
|
+
if (!positions) {
|
|
134
|
+
const network = el("flow-network"), rect = network.getBoundingClientRect(), hub = el("flow-hub").getBoundingClientRect(), edges = [];
|
|
135
|
+
const inset = rect.width < 500 ? 2 : 6;
|
|
136
|
+
if (!rect.width) return;
|
|
137
|
+
for (const type of ["apps", "models"]) for (const [id, node] of nodes[type]) {
|
|
138
|
+
if (!node.isConnected) continue;
|
|
139
|
+
const box = node.getBoundingClientRect(), button = node.children[0].getBoundingClientRect(), left = type === "apps";
|
|
140
|
+
const x0 = (left ? box.right : hub.right) - rect.left + inset, y0 = (left ? button.top + button.height / 2 : hub.top + hub.height / 2) - rect.top;
|
|
141
|
+
const x1 = (left ? hub.left : box.left) - rect.left - inset, y1 = (left ? hub.top + hub.height / 2 : button.top + button.height / 2) - rect.top;
|
|
142
|
+
if (x1 <= x0) continue;
|
|
143
|
+
edges.push({ id, type, node, d: rounded(x0, y0, x1, y1), x: left ? x0 : x1, y: left ? y0 : y1, left });
|
|
144
|
+
}
|
|
145
|
+
positions = { width: rect.width, height: rect.height, edges };
|
|
142
146
|
}
|
|
143
|
-
const
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
147
|
+
const { width, height, edges } = positions;
|
|
148
|
+
const next = JSON.stringify([width, height, edges.map(edge => [edge.type, edge.id, edge.d])]);
|
|
149
|
+
const states = edges.map(edge => {
|
|
150
|
+
const matches = rows.filter(row => (edge.left ? row.application : modelKey(row)) === edge.id && related(row));
|
|
151
|
+
return { active: fresh && matches.length > 0, moving: fresh && matches.some(responding), dim: edge.node.dataset.related === "false" };
|
|
152
|
+
});
|
|
153
|
+
const state = JSON.stringify(states), wires = el("flow-wires");
|
|
154
|
+
if (next === geometry && state === wireState) return;
|
|
155
|
+
if (next !== geometry) {
|
|
156
|
+
geometry = next;wires.setAttribute("viewBox", `0 0 ${width} ${height}`);wires.replaceChildren();
|
|
157
|
+
for (const edge of edges) wires.append(svg("path", { d: edge.d }), svg("circle", { r: 2.4 }));
|
|
149
158
|
}
|
|
159
|
+
wireState = state;
|
|
160
|
+
edges.forEach((edge, index) => {
|
|
161
|
+
const value = states[index], path = wires.children[index * 2], dot = wires.children[index * 2 + 1];
|
|
162
|
+
path.setAttribute("class", `flow-wire${value.dim ? " flow-dim" : value.active ? " flow-live" : ""}`);
|
|
163
|
+
dot.setAttribute("class", value.moving ? "flow-packet" : "flow-wait");
|
|
164
|
+
dot.style.display = value.active ? "" : "none";
|
|
165
|
+
dot.style.offsetPath = value.moving ? `path('${edge.d}')` : "none";
|
|
166
|
+
dot.style.animationDelay = edge.left ? "-.9s" : "0s";
|
|
167
|
+
dot.setAttribute("cx", value.moving ? 0 : edge.x);dot.setAttribute("cy", value.moving ? 0 : edge.y);
|
|
168
|
+
});
|
|
150
169
|
}
|
|
151
170
|
function unavailable() { clearTimeout(expiry);expiry = null;fresh = false;deadline = 0;render(); }
|
|
152
171
|
function visibilityChanged() { if (deadline && Date.now() >= deadline) { unavailable();return; }render();draw(); }
|
|
@@ -157,8 +176,8 @@
|
|
|
157
176
|
document.addEventListener("visibilitychange", visibilityChanged);
|
|
158
177
|
globalThis.addEventListener("pagehide", () => { root.dataset.paused = "true"; });
|
|
159
178
|
globalThis.addEventListener("pageshow", visibilityChanged);
|
|
160
|
-
|
|
161
|
-
new MutationObserver(() => { lastSignature = "";render(); }).observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] });
|
|
179
|
+
resize.observe(el("flow-network"));
|
|
180
|
+
new MutationObserver(() => { lastSignature = "";positions = null;render(); }).observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] });
|
|
162
181
|
globalThis.ccdxDashboardFlow = {
|
|
163
182
|
update(data) {
|
|
164
183
|
const parts = [data?.stream_performance, (data?.providers?.claude || data?.providers?.m365?.claude)?.requests?.performance].filter(Boolean);
|
package/src/dashboard/index.html
CHANGED
|
@@ -328,6 +328,8 @@
|
|
|
328
328
|
</details>
|
|
329
329
|
<details class="lower" id="recent-failures" open>
|
|
330
330
|
<summary class="panel-heading"><h2 data-i18n="recent_inference_http_failures">RECENT REQUEST ISSUES</h2><span id="failure-count">requests + events</span></summary>
|
|
331
|
+
<label for="failure-kind" class="sr-only" data-i18n="issue_category">Issue category</label>
|
|
332
|
+
<select id="failure-kind"><option value="issues" data-i18n="issue_replies">Reply issues</option><option value="capability" data-i18n="issue_capabilities">Capability notices</option><option value="connection" data-i18n="issue_connections">Connections and paths</option></select>
|
|
331
333
|
<ol id="failures"><li class="empty" data-i18n="reading_874bf">Reading…</li></ol>
|
|
332
334
|
</details>
|
|
333
335
|
</div>
|
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
const translations = {
|
|
3
|
+
"issue_category": ["Issue category", "问题分类"],
|
|
4
|
+
"issue_replies": ["Reply issues", "回复问题"],
|
|
5
|
+
"issue_capabilities": ["Capability notices", "能力提示"],
|
|
6
|
+
"issue_connections": ["Connections and paths", "连接与路径"],
|
|
7
|
+
"http_categories": ["Generation {inference} · Capabilities {capability} · Methods {protocol} · Paths {route} · Other {other}", "生成 {inference} · 能力 {capability} · 方法 {protocol} · 路径 {route} · 其他 {other}"],
|
|
8
|
+
"no_upstream_call": ["No upstream call", "未调用上游"],
|
|
9
|
+
"repeated_issue": ["{detail} · {count} occurrences", "{detail} · 出现 {count} 次"],
|
|
10
|
+
"reason": ["Reason", "具体原因"],
|
|
11
|
+
"occurrences": ["Occurrences", "出现次数"],
|
|
12
|
+
"capability_cached": ["Recent capability result reused", "沿用近期能力结果"],
|
|
13
|
+
"shared_upstream": ["Shared upstream call", "合并上游调用"],
|
|
14
|
+
"model_not_selected_message": ["This model is not selected for this app.", "此应用尚未选入该模型。"],
|
|
15
|
+
"model_ambiguous_message": ["This model name matches multiple sources. Select its source-specific entry.", "模型同名,请选择明确来源。"],
|
|
16
|
+
"model_catalog_unavailable_message": ["The selected model is not currently available in its source catalog.", "来源目录中暂时没有该模型。"],
|
|
17
|
+
"client_source_disabled_message": ["This app or its model source is turned off.", "应用或模型来源已关闭。"],
|
|
18
|
+
"local_validation_message": ["The request was rejected locally before an upstream call.", "本机校验未通过,未调用上游。"],
|
|
19
|
+
"count_endpoint_missing_message": ["The source's token-count endpoint returned HTTP 404. Message generation is separate.", "上游计数接口返回 404,回复另行处理。"],
|
|
3
20
|
"nightly_update": ["Update overnight", "夜间自动更新"],
|
|
4
21
|
"nightly_risk": ["Updates install a new version and restart CCDX. Continuing a conversation may be affected.", "开启后会自动安装新版并重启 CCDX,可能影响会话续接。"],
|
|
5
22
|
"nightly_window": ["Update window", "更新时间"],
|
|
@@ -1160,6 +1177,12 @@
|
|
|
1160
1177
|
"outcome": "outcome_25a63",
|
|
1161
1178
|
"origin": "origin",
|
|
1162
1179
|
"route": "route",
|
|
1180
|
+
"This model is not selected for this app.": "model_not_selected_message",
|
|
1181
|
+
"This model name matches multiple sources. Select its source-specific entry.": "model_ambiguous_message",
|
|
1182
|
+
"The selected model is not currently available in its source catalog.": "model_catalog_unavailable_message",
|
|
1183
|
+
"This app or its model source is turned off.": "client_source_disabled_message",
|
|
1184
|
+
"The request was rejected locally before an upstream call.": "local_validation_message",
|
|
1185
|
+
"The source's token-count endpoint returned HTTP 404. Message generation is separate.": "count_endpoint_missing_message",
|
|
1163
1186
|
"HTTP request failed; original response was preserved.": "http_request_failed_original_response_was_preserved",
|
|
1164
1187
|
"phase": "phase",
|
|
1165
1188
|
"http_status": "http_status",
|
package/src/dashboard/status.js
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
let contextRequests = [];
|
|
4
4
|
let contextCompactions = {};
|
|
5
5
|
let failureSignature;
|
|
6
|
+
let issueGroups = { issues: [], capability: [], connection: [] }, issueRequests = [];
|
|
7
|
+
element("failure-kind")?.addEventListener?.("change", () => renderFailures(issueGroups[element("failure-kind").value] || [], element("failure-kind").value === "issues" ? issueRequests : []));
|
|
6
8
|
let contextSignature;
|
|
7
9
|
const sourceNames = new Map([["github", "GitHub Copilot"], ["m365", "Microsoft 365"]]);
|
|
8
10
|
|
|
@@ -85,7 +87,7 @@
|
|
|
85
87
|
}
|
|
86
88
|
|
|
87
89
|
function renderFailures(recent, recentRequests = []) {
|
|
88
|
-
const signature = JSON.stringify([recent, recentRequests]);
|
|
90
|
+
const signature = JSON.stringify([element("failure-kind")?.value, recent, recentRequests]);
|
|
89
91
|
if (signature === failureSignature) return;
|
|
90
92
|
failureSignature = signature;
|
|
91
93
|
const list = element("failures");
|
|
@@ -93,7 +95,15 @@
|
|
|
93
95
|
list.replaceChildren();
|
|
94
96
|
const requests = Array.isArray(recentRequests) ? recentRequests.slice(-20) : [];
|
|
95
97
|
const byRequest = new Map(requests.filter((request) => request.request_id).map((request) => [request.request_id, request]));
|
|
96
|
-
const
|
|
98
|
+
const kind = element("failure-kind")?.value || "issues", grouped = new Map();
|
|
99
|
+
const entries = Array.isArray(recent) ? recent : [];
|
|
100
|
+
for (const failure of entries) {
|
|
101
|
+
const key = kind === "issues" ? failure.request_id || `${failure.at}/${failure.code}`
|
|
102
|
+
: JSON.stringify([failure.provider, failure.model, failure.route, failure.code, kind === "capability" ? null : failure.origin, failure.reason]);
|
|
103
|
+
const old = grouped.get(key);
|
|
104
|
+
grouped.set(key, { ...failure, occurrences: (old?.occurrences || 0) + 1, timeline: byRequest.get(failure.request_id) });
|
|
105
|
+
}
|
|
106
|
+
const failures = [...grouped.values()].slice(-10);
|
|
97
107
|
const recorded = new Set(failures.map((failure) => failure.request_id).filter(Boolean));
|
|
98
108
|
for (const request of requests) {
|
|
99
109
|
if (!request.failed || recorded.has(request.request_id)) continue;
|
|
@@ -124,9 +134,13 @@
|
|
|
124
134
|
model: failure.model ? String(failure.model).slice(0, 80) : phrase("unknown_model"),
|
|
125
135
|
code: failure.code ? String(failure.code).slice(0, 80) : phrase("unknown_error"),
|
|
126
136
|
}),
|
|
127
|
-
retry: phrase(failure.retried ? "retry_attempted" : "no_retry"),
|
|
137
|
+
retry: phrase(failure.upstream_attempts === 0 ? "no_upstream_call" : failure.retried ? "retry_attempted" : "no_retry"),
|
|
128
138
|
};
|
|
129
139
|
localize(title, "detail_retry", summary);
|
|
140
|
+
if (failure.occurrences > 1) {
|
|
141
|
+
summary.detail = phrase("repeated_issue", { detail: summary.detail, count: failure.occurrences });
|
|
142
|
+
localize(title, "detail_retry", summary);
|
|
143
|
+
}
|
|
130
144
|
const timeline = failure.timeline;
|
|
131
145
|
const provider = failure.provider || timeline?.provider;
|
|
132
146
|
if (provider) {
|
|
@@ -137,7 +151,7 @@
|
|
|
137
151
|
const timings = timeline?.timings_ms || {};
|
|
138
152
|
const timingText = ["admission", "body", "history", "images", "serialization", "upstream_start", "upstream_headers", "first_output", "last_activity", "terminal", "finished"]
|
|
139
153
|
.filter((key) => finite(timings[key])).map((key) => `${key}=${Number(timings[key]).toFixed(1)}`).join(" / ");
|
|
140
|
-
const fields = { time: failure.at, model: failure.model, event: failure.event_type, code: failure.code,
|
|
154
|
+
const fields = { time: failure.at, model: failure.model, event: failure.event_type, code: failure.code, reason: failure.reason, application: failure.application, occurrences: failure.occurrences > 1 ? failure.occurrences : undefined, capability_cached: failure.capability_cached, shared_upstream: failure.shared_upstream,
|
|
141
155
|
message: failure.message, response_id: failure.response_id, upstream_request_id: failure.upstream_request_id,
|
|
142
156
|
retry: failure.retried ? (timeline ? "attempted" : "attempted (outcome not recorded here)") : "not attempted",
|
|
143
157
|
retry_policy: failure.retry_policy, retry_skipped: failure.retry_skipped,
|
|
@@ -197,8 +211,8 @@
|
|
|
197
211
|
text("requests", number(requests.total));
|
|
198
212
|
text("request-errors", "4xx_client_5xx_server_active_active", { client: number(requests.status_4xx), server: number(requests.status_5xx), active: number(requests.active) });
|
|
199
213
|
const categories = data.http_errors?.by_category;
|
|
200
|
-
text("http-error-breakdown", categories ? "
|
|
201
|
-
categories ? Object.fromEntries(
|
|
214
|
+
text("http-error-breakdown", categories ? "http_categories" : "—",
|
|
215
|
+
categories ? Object.fromEntries(["inference", "capability", "protocol", "route", "other"].map(key => [key, number(categories[key] || 0)])) : {});
|
|
202
216
|
text("body-limits", "raw_raw_decoded_decoded", { raw: mib(data.limits?.max_body_bytes), decoded: mib(data.limits?.max_decoded_body_bytes) });
|
|
203
217
|
|
|
204
218
|
const outcomes = data.stream_performance?.by_route?.responses?.terminal_outcomes?.totals || {};
|
|
@@ -241,8 +255,15 @@
|
|
|
241
255
|
}
|
|
242
256
|
const recentRequests = [...(data.stream_performance?.recent_requests || []), ...(claudeMetrics?.recent_requests || [])]
|
|
243
257
|
.sort((a, b) => (Date.parse(a.at) || 0) - (Date.parse(b.at) || 0));
|
|
244
|
-
|
|
245
|
-
|
|
258
|
+
issueGroups = {
|
|
259
|
+
issues: [...(data.response_failures?.recent || []), ...(data.http_errors?.actionable_recent || data.http_errors?.recent || [])],
|
|
260
|
+
capability: data.http_errors?.capability_recent || [],
|
|
261
|
+
connection: [...(data.http_errors?.protocol_recent || []), ...(data.http_errors?.route_recent || [])],
|
|
262
|
+
};
|
|
263
|
+
for (const rows of Object.values(issueGroups)) rows.sort((a, b) => (Date.parse(a.at) || 0) - (Date.parse(b.at) || 0));
|
|
264
|
+
issueRequests = recentRequests;
|
|
265
|
+
const kind = element("failure-kind")?.value || "issues";
|
|
266
|
+
renderFailures(issueGroups[kind] || [], kind === "issues" ? recentRequests : []);
|
|
246
267
|
renderContext({ ...data.stream_performance, recent_requests: recentRequests });
|
|
247
268
|
if (element("claude-route")) {
|
|
248
269
|
element("claude-route").textContent = claude?.base_url || "—";
|
package/src/dashboard/ui.css
CHANGED
|
@@ -526,3 +526,5 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
526
526
|
|
|
527
527
|
.nightly-update { margin:26px 0; }.nightly-rules { display:grid;grid-template-columns:1fr 1fr;gap:20px 30px;margin:22px 0; }.nightly-rules dt { color:var(--muted);font-size:11px;margin-bottom:8px; }.nightly-rules dd { margin:0;font-size:12px;line-height:1.7; }
|
|
528
528
|
@media(max-width:640px) { .nightly-rules { grid-template-columns:1fr; } }
|
|
529
|
+
|
|
530
|
+
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
|
|
3
|
+
import { readBoundedResponseText } from "../http-transport.mjs";
|
|
4
|
+
|
|
5
|
+
// Owned by one immutable API/key configuration. No conversation or credential
|
|
6
|
+
// is cached; only small response envelopes and bounded in-flight hashes exist.
|
|
7
|
+
export function createApiTokenCounter({ request, now = Date.now }) {
|
|
8
|
+
const flights = new Map(), unavailable = new Map(), shared = createAbortAwareSingleflight();
|
|
9
|
+
let bytes = 0;
|
|
10
|
+
const missed = () => new Response(JSON.stringify({ type: "error", error: { type: "api_error",
|
|
11
|
+
code: "ccdx_api_count_tokens_unavailable", message: "This source's token-count endpoint returned HTTP 404. Message generation is separate." } }),
|
|
12
|
+
{ status: 404, headers: { "Content-Type": "application/json" } });
|
|
13
|
+
return {
|
|
14
|
+
async count(body, options = {}) {
|
|
15
|
+
if (options.signal?.aborted) throw options.signal.reason;
|
|
16
|
+
const headers = Object.fromEntries(["anthropic-version", "anthropic-beta"].map(name => [name, options.headers?.[name] || ""]));
|
|
17
|
+
const scope = createHash("sha256").update(JSON.stringify([body.model, headers])).digest("hex");
|
|
18
|
+
const at = now(), seen = unavailable.get(scope);
|
|
19
|
+
if (seen !== undefined && at >= seen && at - seen < 60000) { options.onCountObservation?.({ cached: true });return missed(); }
|
|
20
|
+
unavailable.delete(scope);
|
|
21
|
+
const serialized = JSON.stringify(body), size = Buffer.byteLength(serialized);
|
|
22
|
+
const key = size <= 1024 * 1024 ? createHash("sha256").update(scope).update(serialized).digest("hex") : null;
|
|
23
|
+
const waiter = { start: options.onUpstreamStart, observe: options.onCountObservation, signal: options.signal };
|
|
24
|
+
let flight = flights.get(key);
|
|
25
|
+
if (flight && [...flight.waiters].every(item => item.signal?.aborted)) {
|
|
26
|
+
flights.delete(key);bytes -= size;flight = null;
|
|
27
|
+
}
|
|
28
|
+
const joinable = Boolean(flight) || size <= 1024 * 1024 && flights.size < 16 && bytes + size <= 4 * 1024 * 1024;
|
|
29
|
+
if (!flight) {
|
|
30
|
+
flight = { key: {}, waiters: new Set(), started: false, shared: false };
|
|
31
|
+
if (joinable) { flights.set(key, flight);bytes += size; }
|
|
32
|
+
} else flight.shared = true;
|
|
33
|
+
flight.waiters.add(waiter);
|
|
34
|
+
const start = item => { item.start?.();item.observe?.({ upstream: true, shared: flight.shared }); };
|
|
35
|
+
if (flight.started) start(waiter);
|
|
36
|
+
const run = async signal => {
|
|
37
|
+
try {
|
|
38
|
+
if (signal?.aborted) throw signal.reason;
|
|
39
|
+
const response = await request(body, { ...options, bodyText: serialized, signal, observeUpstream: false,
|
|
40
|
+
onUpstreamStart() { flight.started = true;for (const item of flight.waiters) start(item); } });
|
|
41
|
+
if (signal?.aborted) { await response.body?.cancel();throw signal.reason; }
|
|
42
|
+
if (response.status === 404) {
|
|
43
|
+
await response.body?.cancel();unavailable.set(scope, now());
|
|
44
|
+
while (unavailable.size > 128) unavailable.delete(unavailable.keys().next().value);
|
|
45
|
+
const result = missed();return { status: result.status, headers: [...result.headers], text: await result.text() };
|
|
46
|
+
}
|
|
47
|
+
const text = await readBoundedResponseText(response, { maxBytes: 64 * 1024, label: "API token count", signal });
|
|
48
|
+
return { status: response.status, headers: [...response.headers], text };
|
|
49
|
+
} finally { if (joinable && flights.get(key) === flight) { flights.delete(key);bytes -= size; } }
|
|
50
|
+
};
|
|
51
|
+
try {
|
|
52
|
+
const result = joinable ? await shared.run(flight.key, run, { signal: options.signal }) : await run(options.signal);
|
|
53
|
+
options.onCountObservation?.({ shared: flight.shared });
|
|
54
|
+
return new Response(result.text || null, { status: result.status, headers: result.headers });
|
|
55
|
+
} finally {
|
|
56
|
+
flight.waiters.delete(waiter);
|
|
57
|
+
if (!flight.waiters.size && joinable && flights.get(key) === flight) { flights.delete(key);bytes -= size; }
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
package/src/providers/api.mjs
CHANGED
|
@@ -12,8 +12,9 @@ import { checkedApiKey } from "../api-secrets.mjs";
|
|
|
12
12
|
import { transportErrorDetails } from "../operation-error.mjs";
|
|
13
13
|
import { resolveModelCapabilities, deploymentRevision, constrainModelRequest } from "../model-capabilities.mjs";
|
|
14
14
|
import { apiModelMetadata } from "./api-model-metadata.mjs";
|
|
15
|
-
import { markRequestObservation } from "../stream-performance.mjs";
|
|
15
|
+
import { markRequestObservation, markUpstreamStarted } from "../stream-performance.mjs";
|
|
16
16
|
import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
|
|
17
|
+
import { createApiTokenCounter } from "./api-token-count.mjs";
|
|
17
18
|
|
|
18
19
|
const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
|
|
19
20
|
export function apiCatalog(config, env = process.env) {
|
|
@@ -71,6 +72,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
71
72
|
const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
|
|
72
73
|
if (serialized !== undefined) headers["Content-Length"] = String(Buffer.byteLength(serialized));
|
|
73
74
|
options.onUpstreamStart?.();
|
|
75
|
+
if (body && options.observeUpstream !== false) markUpstreamStarted(body.stream === true);
|
|
74
76
|
try {
|
|
75
77
|
const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
|
|
76
78
|
if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
|
|
@@ -91,6 +93,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
91
93
|
throw failure;
|
|
92
94
|
}
|
|
93
95
|
}
|
|
96
|
+
const counter = createApiTokenCounter({ request: (body, options) => request(config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens", body, options, "messages") });
|
|
94
97
|
const client = {
|
|
95
98
|
listModels: async () => ({ status: 200, body: JSON.stringify(registry.models) }),
|
|
96
99
|
getCachedModelEndpoints: id => catalog.find(model => model.id === id)?.supported_endpoints || null,
|
|
@@ -106,7 +109,8 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
106
109
|
chatCompletions(body, options = {}) { selected(body.model, "chat");return request(config.endpoints.chat, body, options, "chat"); },
|
|
107
110
|
messages(body, options = {}) {
|
|
108
111
|
const model = selected(body.model, "messages");
|
|
109
|
-
|
|
112
|
+
const outgoing = model.id === body.model ? body : { ...body, model: model.id };
|
|
113
|
+
return options.countTokens ? counter.count(outgoing, options) : request(config.endpoints.messages, outgoing, options, "messages");
|
|
110
114
|
},
|
|
111
115
|
};
|
|
112
116
|
return {
|
|
@@ -122,7 +126,11 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
122
126
|
const models = [], ids = new Set(), checked_at = new Date().toISOString();let url = modelsUrl, bytes = 0;
|
|
123
127
|
for (let page = 0; page < 25; page++) {
|
|
124
128
|
const response = await request(url, undefined, { signal }, config.endpoints.responses ? "responses" : "messages");
|
|
125
|
-
if (!response.ok) {
|
|
129
|
+
if (!response.ok) {
|
|
130
|
+
await response.body?.cancel();const error = accessError(`ccdx_api_catalog_http_${response.status}`, response.status === 401 || response.status === 403 ? response.status : 502);
|
|
131
|
+
const retry = response.headers.get("retry-after"), delay = /^\d{1,8}$/.test(retry || "") ? Number(retry) * 1000 : Date.parse(retry) - Date.now();
|
|
132
|
+
if (Number.isFinite(delay) && delay > 0) error.retryAfterMs = Math.min(delay, 86400000);throw error;
|
|
133
|
+
}
|
|
126
134
|
const text = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES - bytes, label: "API model catalog", signal });bytes += Buffer.byteLength(text);
|
|
127
135
|
let value;try { value = JSON.parse(text); } catch { throw accessError("ccdx_api_catalog_invalid", 502); }
|
|
128
136
|
if (!Array.isArray(value.data) || models.length + value.data.length > 500) throw accessError("ccdx_api_catalog_invalid", 502);
|
package/src/request-context.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
3
4
|
|
|
4
5
|
const requestContextStorage = new AsyncLocalStorage();
|
|
5
6
|
|
|
@@ -14,3 +15,10 @@ export function runWithRequestContext(context, callback) {
|
|
|
14
15
|
export function currentRequestContext() {
|
|
15
16
|
return requestContextStorage.getStore() || null;
|
|
16
17
|
}
|
|
18
|
+
|
|
19
|
+
// Capture before route validation; never retain a body or an arbitrary string.
|
|
20
|
+
export function observeRequestedModel(body) {
|
|
21
|
+
const value = body?.model, context = currentRequestContext();
|
|
22
|
+
if (context && typeof value === "string" && /^[\w][\w./:@+-]{0,159}$/.test(value)
|
|
23
|
+
&& redactDiagnosticText(value) === value) { context.requestedModel = value;context.streamPerformance?.setModel?.(value); }
|
|
24
|
+
}
|
|
@@ -138,26 +138,43 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
|
|
|
138
138
|
const all = createResponseFailureDiagnostics({ maxEntries, now });
|
|
139
139
|
const actionable = createResponseFailureDiagnostics({ maxEntries, now });
|
|
140
140
|
const protocol = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
141
|
-
const
|
|
141
|
+
const capability = createResponseFailureDiagnostics({ maxEntries: 20, now });
|
|
142
|
+
const routes = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
143
|
+
const counts = { inference: 0, capability: 0, protocol: 0, route: 0, other: 0 };
|
|
142
144
|
return {
|
|
143
145
|
record(details) {
|
|
144
146
|
all.record(details);
|
|
145
|
-
const category =
|
|
147
|
+
const category = details.route === "messages_count_tokens" ? "capability"
|
|
148
|
+
: ["responses", "responses_compact", "messages"].includes(details.route) ? "inference"
|
|
146
149
|
: details.route === "image_mcp" && details.http_status === 405 ? "protocol"
|
|
147
150
|
: details.route === "not_found" ? "route" : "other";
|
|
148
151
|
counts[category]++;
|
|
149
152
|
if (category === "inference" || category === "other") actionable.record(details);
|
|
153
|
+
if (category === "capability") {
|
|
154
|
+
capability.record(details);
|
|
155
|
+
if (![404, 405, 501].includes(details.http_status)) actionable.record(details);
|
|
156
|
+
}
|
|
150
157
|
if (category === "protocol") protocol.record(details);
|
|
158
|
+
if (category === "route") routes.record(details);
|
|
151
159
|
},
|
|
152
160
|
snapshot() { return { ...all.snapshot(), by_category: { ...counts },
|
|
153
|
-
actionable_recent: actionable.snapshot().recent,
|
|
161
|
+
actionable_recent: actionable.snapshot().recent, capability_recent: capability.snapshot().recent,
|
|
162
|
+
protocol_recent: protocol.snapshot().recent, route_recent: routes.snapshot().recent }; },
|
|
154
163
|
};
|
|
155
164
|
}
|
|
156
165
|
|
|
157
166
|
export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers,
|
|
158
|
-
error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider
|
|
167
|
+
error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
|
|
168
|
+
application, reason, capability_cached, shared_upstream }) {
|
|
169
|
+
const reasons = { ccdx_model_not_selected: "This model is not selected for this app.",
|
|
170
|
+
ccdx_model_ambiguous: "This model name matches multiple sources. Select its source-specific entry.",
|
|
171
|
+
ccdx_model_catalog_unavailable: "The selected model is not currently available in its source catalog.",
|
|
172
|
+
ccdx_client_source_disabled: "This app or its model source is turned off." };
|
|
173
|
+
const message = (Object.hasOwn(reasons, reason) ? reasons[reason] : null) || (route === "messages_count_tokens" && statusCode === 404 ? "The source's token-count endpoint returned HTTP 404. Message generation is separate."
|
|
174
|
+
: origin === "client_validation" ? "The request was rejected locally before an upstream call."
|
|
175
|
+
: error_body === "empty" ? "Upstream returned no error details." : "HTTP request failed; original response was preserved.");
|
|
159
176
|
const details = responseFailureDetails({ model, error: { code: typeof code === "string" && /^[a-z\d_.:-]{1,80}$/i.test(code) ? code : `http_${statusCode}`,
|
|
160
|
-
message
|
|
177
|
+
message } }, "http.error", { headers, provider });
|
|
161
178
|
return { ...details, request_id: requestId, http_status: statusCode, route,
|
|
162
179
|
origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true,
|
|
163
180
|
...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}), ...(parameter ? { parameter } : {}),
|
|
@@ -166,5 +183,8 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
|
|
|
166
183
|
...(request_options ? { request_options } : {}),
|
|
167
184
|
...(attempt_timings ? { attempt_timings } : {}),
|
|
168
185
|
...(requested_model ? { requested_model, request_kind: requested_model === "codex-auto-review" ? "auto_review" : "unknown" } : {}),
|
|
186
|
+
...(["codex_app", "codex_cli", "codex", "claude_app", "claude_code", "claude", "api"].includes(application) ? { application } : {}),
|
|
187
|
+
...(Object.hasOwn(reasons, reason) ? { reason } : {}),
|
|
188
|
+
...(capability_cached === true ? { capability_cached: true } : {}), ...(shared_upstream === true ? { shared_upstream: true } : {}),
|
|
169
189
|
...(Number.isSafeInteger(upstream_attempts) ? { upstream_attempts } : {}) };
|
|
170
190
|
}
|
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
responseHistoryPressureRootId,
|
|
31
31
|
} from "./responses-request.mjs";
|
|
32
32
|
import { status } from "./status.mjs";
|
|
33
|
+
import { observeRequestedModel } from "./request-context.mjs";
|
|
33
34
|
import { endStreamWithError } from "./stream-errors.mjs";
|
|
34
35
|
import { createSseKeepalive } from "./sse-keepalive.mjs";
|
|
35
36
|
import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
|
|
@@ -206,6 +207,7 @@ export function createResponsesHandler(options) {
|
|
|
206
207
|
releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
|
|
207
208
|
abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
|
|
208
209
|
parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
|
|
210
|
+
observeRequestedModel(parsed);
|
|
209
211
|
const selectedProvider = options.resolveProvider?.(parsed, req);
|
|
210
212
|
if (selectedProvider) {
|
|
211
213
|
provider = selectedProvider;modelRegistry = provider.registry;
|
|
@@ -489,6 +491,7 @@ export function createResponsesCompactHandler(options) {
|
|
|
489
491
|
releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
|
|
490
492
|
abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
|
|
491
493
|
const parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
|
|
494
|
+
observeRequestedModel(parsed);
|
|
492
495
|
const selectedProvider = options.resolveProvider?.(parsed, req);
|
|
493
496
|
if (selectedProvider) {
|
|
494
497
|
provider = selectedProvider;modelRegistry = provider.registry;
|
|
@@ -458,6 +458,8 @@ export async function measureRequestStageAsync(stage, operation) {
|
|
|
458
458
|
}
|
|
459
459
|
|
|
460
460
|
export function markUpstreamStarted(streaming = true) {
|
|
461
|
+
const context = currentRequestContext();
|
|
462
|
+
if (context) context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;
|
|
461
463
|
tracker()?.upstreamStarted(streaming);
|
|
462
464
|
}
|
|
463
465
|
|
|
@@ -489,7 +491,7 @@ export function markResponseModel(model, { requestedModel, configuredModel = fal
|
|
|
489
491
|
const context = currentRequestContext();
|
|
490
492
|
if (context) {
|
|
491
493
|
context.model = model;
|
|
492
|
-
if (requestedModel !== undefined) context.requestedModel = modelLabel(requestedModel);
|
|
494
|
+
if (requestedModel !== undefined && context.requestedModel === undefined) context.requestedModel = modelLabel(requestedModel);
|
|
493
495
|
}
|
|
494
496
|
tracker()?.setModel?.(model, { configured: configuredModel });
|
|
495
497
|
}
|