codex-copilot-dx 1.2.22 → 1.2.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/docs/ARCHITECTURE.md +56 -0
- package/docs/REFERENCE.md +110 -5
- package/package.json +1 -1
- package/src/adapter.mjs +8 -5
- package/src/api-catalog-refresh.mjs +7 -4
- package/src/api-model-display.mjs +47 -0
- package/src/claude-gateway.mjs +35 -10
- package/src/cli-status.mjs +2 -2
- package/src/codex-memory-model.mjs +64 -0
- package/src/codex-memory-probe.mjs +25 -0
- package/src/connection-runtime.mjs +31 -9
- package/src/conversation-source-guard.mjs +3 -1
- package/src/dashboard/connections.js +61 -7
- package/src/dashboard/console.js +6 -1
- package/src/dashboard/flow.js +40 -26
- package/src/dashboard/index.html +7 -0
- package/src/dashboard/language.js +52 -0
- package/src/dashboard/status.js +42 -14
- package/src/dashboard/ui.css +31 -6
- package/src/dashboard/ui.js +5 -2
- package/src/provider-metadata.mjs +2 -2
- package/src/providers/api-token-count.mjs +66 -0
- package/src/providers/api.mjs +21 -7
- package/src/providers/m365.mjs +1 -1
- package/src/request-context.mjs +8 -0
- package/src/response-failures.mjs +34 -6
- package/src/responses-handler.mjs +5 -0
- package/src/stream-performance.mjs +10 -4
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,13 +95,21 @@
|
|
|
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
|
-
if (!request.failed || recorded.has(request.request_id)) continue;
|
|
109
|
+
if (!request.failed || request.outcome === "cancelled" || request.rejection_reason || recorded.has(request.request_id)) continue;
|
|
100
110
|
failures.push({ at: request.at, model: request.model, request_id: request.request_id,
|
|
101
111
|
event_type: `request.${request.outcome}`, code: request.origin, timeline: request,
|
|
102
|
-
message: "Request ended without successful completion.", local_message: true, retried: request.upstream_attempts > 1 });
|
|
112
|
+
message: request.stop_reason === "max_tokens" ? "Output limit reached." : "Request ended without successful completion.", local_message: true, retried: request.upstream_attempts > 1 });
|
|
103
113
|
}
|
|
104
114
|
failures.sort((a, b) => (Date.parse(a.at) || 0) - (Date.parse(b.at) || 0));
|
|
105
115
|
failures.splice(0, Math.max(0, failures.length - 10));
|
|
@@ -113,6 +123,7 @@
|
|
|
113
123
|
return;
|
|
114
124
|
}
|
|
115
125
|
for (const failure of failures) {
|
|
126
|
+
const notModelRequest = ["not_found", "image_mcp", "models", "claude_models"].includes(failure.route);
|
|
116
127
|
const item = document.createElement("li");
|
|
117
128
|
const details = document.createElement("details");
|
|
118
129
|
details.dataset.key = `${failure.at}/${failure.request_id || failure.response_id}/${failure.code}`;
|
|
@@ -121,12 +132,16 @@
|
|
|
121
132
|
const summary = {
|
|
122
133
|
detail: phrase("time_model_code", {
|
|
123
134
|
time: failure.at ? time(failure.at, { date: true }) : phrase("unknown_time"),
|
|
124
|
-
model: failure.model ? String(failure.model).slice(0, 80) : phrase("unknown_model"),
|
|
135
|
+
model: notModelRequest ? phrase("not_applicable") : failure.model ? String(failure.model).slice(0, 80) : phrase("unknown_model"),
|
|
125
136
|
code: failure.code ? String(failure.code).slice(0, 80) : phrase("unknown_error"),
|
|
126
137
|
}),
|
|
127
|
-
retry: phrase(failure.retried ? "retry_attempted" : "no_retry"),
|
|
138
|
+
retry: phrase(failure.upstream_attempts === 0 ? "no_upstream_call" : failure.retried ? "retry_attempted" : "no_retry"),
|
|
128
139
|
};
|
|
129
140
|
localize(title, "detail_retry", summary);
|
|
141
|
+
if (failure.occurrences > 1) {
|
|
142
|
+
summary.detail = phrase("repeated_issue", { detail: summary.detail, count: failure.occurrences });
|
|
143
|
+
localize(title, "detail_retry", summary);
|
|
144
|
+
}
|
|
130
145
|
const timeline = failure.timeline;
|
|
131
146
|
const provider = failure.provider || timeline?.provider;
|
|
132
147
|
if (provider) {
|
|
@@ -137,7 +152,7 @@
|
|
|
137
152
|
const timings = timeline?.timings_ms || {};
|
|
138
153
|
const timingText = ["admission", "body", "history", "images", "serialization", "upstream_start", "upstream_headers", "first_output", "last_activity", "terminal", "finished"]
|
|
139
154
|
.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,
|
|
155
|
+
const fields = { time: failure.at, model: notModelRequest ? phrase("not_applicable") : 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
156
|
message: failure.message, response_id: failure.response_id, upstream_request_id: failure.upstream_request_id,
|
|
142
157
|
retry: failure.retried ? (timeline ? "attempted" : "attempted (outcome not recorded here)") : "not attempted",
|
|
143
158
|
retry_policy: failure.retry_policy, retry_skipped: failure.retry_skipped,
|
|
@@ -148,7 +163,9 @@
|
|
|
148
163
|
error_type: failure.error_type, parameter: failure.parameter, error_body: failure.error_body,
|
|
149
164
|
diagnostic_message: failure.diagnostic_message, method: failure.method, target: failure.target,
|
|
150
165
|
request_options: failure.request_options ? JSON.stringify(failure.request_options) : undefined,
|
|
151
|
-
|
|
166
|
+
transport: failure.transport ? JSON.stringify(failure.transport) : undefined,
|
|
167
|
+
output_requested: timeline?.context?.max_output_tokens_requested, output_sent: timeline?.context?.max_output_tokens_sent,
|
|
168
|
+
output_used: timeline?.context?.output_tokens, stop_reason: timeline?.stop_reason, requested_model: failure.requested_model, request_kind: failure.request_kind, provider: failure.provider || timeline?.provider,
|
|
152
169
|
attempt_timings: failure.attempt_timings || timeline?.attempts ? JSON.stringify(failure.attempt_timings || timeline.attempts) : undefined,
|
|
153
170
|
timings_ms: timingText };
|
|
154
171
|
const diagnostic = document.createElement("dl");
|
|
@@ -184,6 +201,7 @@
|
|
|
184
201
|
|
|
185
202
|
function render(data) {
|
|
186
203
|
for (const source of data.providers?.connections?.providers || []) sourceNames.set(source.id, source.name);
|
|
204
|
+
globalThis.ccdxConnections?.updateMemory?.(data.providers?.connections);
|
|
187
205
|
globalThis.ccdxDashboardActivity?.update(data.model_activity);
|
|
188
206
|
globalThis.ccdxDashboardFlow?.update(data);
|
|
189
207
|
text("version", `v${data.version || "?"}`);
|
|
@@ -197,8 +215,8 @@
|
|
|
197
215
|
text("requests", number(requests.total));
|
|
198
216
|
text("request-errors", "4xx_client_5xx_server_active_active", { client: number(requests.status_4xx), server: number(requests.status_5xx), active: number(requests.active) });
|
|
199
217
|
const categories = data.http_errors?.by_category;
|
|
200
|
-
text("http-error-breakdown", categories ? "
|
|
201
|
-
categories ? Object.fromEntries(
|
|
218
|
+
text("http-error-breakdown", categories ? "http_categories" : "—",
|
|
219
|
+
categories ? Object.fromEntries(["inference", "capability", "protocol", "route", "other"].map(key => [key, number(categories[key] || 0)])) : {});
|
|
202
220
|
text("body-limits", "raw_raw_decoded_decoded", { raw: mib(data.limits?.max_body_bytes), decoded: mib(data.limits?.max_decoded_body_bytes) });
|
|
203
221
|
|
|
204
222
|
const outcomes = data.stream_performance?.by_route?.responses?.terminal_outcomes?.totals || {};
|
|
@@ -241,8 +259,15 @@
|
|
|
241
259
|
}
|
|
242
260
|
const recentRequests = [...(data.stream_performance?.recent_requests || []), ...(claudeMetrics?.recent_requests || [])]
|
|
243
261
|
.sort((a, b) => (Date.parse(a.at) || 0) - (Date.parse(b.at) || 0));
|
|
244
|
-
|
|
245
|
-
|
|
262
|
+
issueGroups = {
|
|
263
|
+
issues: [...(data.response_failures?.recent || []), ...(data.http_errors?.actionable_recent || data.http_errors?.recent || [])],
|
|
264
|
+
capability: data.http_errors?.capability_recent || [],
|
|
265
|
+
connection: [...(data.http_errors?.protocol_recent || []), ...(data.http_errors?.route_recent || [])],
|
|
266
|
+
};
|
|
267
|
+
for (const rows of Object.values(issueGroups)) rows.sort((a, b) => (Date.parse(a.at) || 0) - (Date.parse(b.at) || 0));
|
|
268
|
+
issueRequests = recentRequests;
|
|
269
|
+
const kind = element("failure-kind")?.value || "issues";
|
|
270
|
+
renderFailures(issueGroups[kind] || [], kind === "issues" ? recentRequests : []);
|
|
246
271
|
renderContext({ ...data.stream_performance, recent_requests: recentRequests });
|
|
247
272
|
if (element("claude-route")) {
|
|
248
273
|
element("claude-route").textContent = claude?.base_url || "—";
|
|
@@ -305,7 +330,9 @@
|
|
|
305
330
|
String(sourceLabel(request.provider) || "—").slice(0, 80),
|
|
306
331
|
String(request.model || "unknown").slice(0, 80), outcome, number(context.input_tokens), ""], { labels: [3] });
|
|
307
332
|
const wireFailure = Number.isInteger(request.http_status) && request.http_status >= 400;
|
|
308
|
-
if (
|
|
333
|
+
if (request.rejection_reason) {
|
|
334
|
+
if (globalThis.ccdxIcons) globalThis.ccdxIcons.set(row.children[3], "request_access_blocked", "unavailable");else localize(row.children[3], "request_access_blocked");
|
|
335
|
+
} else if (globalThis.ccdxIcons) globalThis.ccdxIcons.set(row.children[3], wireFailure ? "request_http_failure" : outcome.toLowerCase(),
|
|
309
336
|
wireFailure ? "warning" : globalThis.ccdxIcons.kind(outcome.toLowerCase()), wireFailure ? { status: request.http_status } : {});
|
|
310
337
|
else if (wireFailure) localize(row.children[3], "request_http_failure", { status: request.http_status });
|
|
311
338
|
const details = document.createElement("details"), summary = document.createElement("summary"), fields = document.createElement("dl");
|
|
@@ -316,7 +343,8 @@
|
|
|
316
343
|
for (const [key, value] of [["request_id", request.request_id || "—"], ["http_status", number(request.http_status)], ["attempts", number(request.upstream_attempts)], ["model_outcome", globalThis.ccdxLanguage?.format(outcome.toLowerCase()) || outcome],
|
|
317
344
|
["time", Number.isFinite(at) ? time(at, { date: true }) : "—"],
|
|
318
345
|
["wire_mib", finite(context.payload_bytes) ? `${(Number(context.payload_bytes) / 1048576).toFixed(2)} MiB` : "—"],
|
|
319
|
-
["images", number(context.images)], ["model_window", number(context.context_window_tokens)], ["input_window", ratio]
|
|
346
|
+
["images", number(context.images)], ["model_window", number(context.context_window_tokens)], ["input_window", ratio],
|
|
347
|
+
["output_requested", number(context.max_output_tokens_requested)], ["output_sent", number(context.max_output_tokens_sent)], ["output_used", number(context.output_tokens)], ["stop_reason", request.stop_reason || "—"]]) {
|
|
320
348
|
const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);detail.textContent = value;fields.append(term, detail);
|
|
321
349
|
}
|
|
322
350
|
row.children[5].append(details);body.append(row);
|
package/src/dashboard/ui.css
CHANGED
|
@@ -461,14 +461,14 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
461
461
|
.flow-caption { display:flex;align-items:center;flex-wrap:wrap;gap:10px 16px;min-height:30px;font-size:11px;color:var(--muted); }
|
|
462
462
|
.flow-caption button { padding:5px 9px; }
|
|
463
463
|
.flow-wire { fill:none;stroke:var(--border);stroke-width:1;stroke-linecap:round;stroke-linejoin:round; }
|
|
464
|
-
.flow-live { stroke:var(--accent);opacity:.
|
|
464
|
+
.flow-live { stroke:var(--accent);opacity:.68; }
|
|
465
465
|
.flow-dim { opacity:.35; }
|
|
466
|
-
.flow-
|
|
467
|
-
.flow-
|
|
468
|
-
#request-flow[data-paused="true"] .flow-
|
|
466
|
+
.flow-streaming { stroke-dasharray:4 8;animation:flow-dash 1.5s linear infinite; }
|
|
467
|
+
.flow-waiting { stroke-dasharray:4 8; }
|
|
468
|
+
#request-flow[data-paused="true"] .flow-streaming,#request-flow[data-paused="true"] #flow-state::before { animation-play-state:paused; }
|
|
469
469
|
#request-flow[data-state="idle"] #flow-state { display:inline-flex;align-items:center;gap:9px; }
|
|
470
470
|
#request-flow[data-state="idle"] #flow-state::before { content:"";width:4px;height:4px;border-radius:50%;background:var(--accent);box-shadow:0 0 10px 3px color-mix(in srgb,var(--accent) 25%,transparent);animation:flow-breathe 3.2s ease-in-out infinite; }
|
|
471
|
-
@keyframes flow-
|
|
471
|
+
@keyframes flow-dash { from { stroke-dashoffset:0; } to { stroke-dashoffset:24; } }
|
|
472
472
|
@keyframes flow-breathe { 0%,100% { opacity:.45; } 50% { opacity:1; } }
|
|
473
473
|
@media(max-width:760px) {
|
|
474
474
|
.flow-network { grid-template-columns:minmax(105px,1fr) 66px minmax(120px,1fr);column-gap:18px; }
|
|
@@ -484,7 +484,7 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
484
484
|
.flow-logo { width:26px;height:26px; }
|
|
485
485
|
#flow-hub,.flow-halo { width:48px;height:48px; }
|
|
486
486
|
}
|
|
487
|
-
@media(prefers-reduced-motion:reduce) { .flow-
|
|
487
|
+
@media(prefers-reduced-motion:reduce) { .flow-streaming,.flow-halo-turn,#request-flow[data-state="idle"] #flow-state::before { animation:none;transition:none; } }
|
|
488
488
|
|
|
489
489
|
/* Model capability and application binding controls share the existing palette. */
|
|
490
490
|
.client-segments { margin-bottom: 18px; }
|
|
@@ -526,3 +526,28 @@ 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; }
|
|
531
|
+
|
|
532
|
+
#flow-models { align-items:stretch; }
|
|
533
|
+
#flow-models .flow-node { width:100%; }
|
|
534
|
+
#flow-models .flow-choice { text-align:left; }
|
|
535
|
+
.flow-column:last-child .flow-column-title { text-align:left;padding-left:9px; }
|
|
536
|
+
.model-maker { display:block;margin-top:5px;color:var(--muted);font-size:11px;font-weight:400; }
|
|
537
|
+
.model-identity { display:grid;grid-template-columns:auto 1fr;gap:8px 16px;font-size:12px;margin:18px 0; }
|
|
538
|
+
.model-identity dt { color:var(--muted); }
|
|
539
|
+
.model-identity dd { margin:0;overflow-wrap:anywhere; }
|
|
540
|
+
.memory-model-row { display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;padding:18px 0; }
|
|
541
|
+
.memory-model-value { display:flex;align-items:center;gap:12px;flex-wrap:wrap; }
|
|
542
|
+
.memory-model-notice { margin:0 0 18px;color:var(--incomplete);font-size:12px;line-height:1.7; }
|
|
543
|
+
.memory-model-badge { display:block;margin:5px 0 0 23px;color:var(--muted);font-size:11px; }
|
|
544
|
+
.memory-confirm { width:min(430px,calc(100% - 32px));border:1px solid var(--button-border);border-radius:2px;background:var(--surface);color:var(--text);padding:24px;font:inherit; }
|
|
545
|
+
.memory-confirm::backdrop { background:color-mix(in srgb,var(--page) 70%,transparent);backdrop-filter:blur(2px); }
|
|
546
|
+
.memory-confirm h2 { margin:0;color:var(--strong);font-size:18px; }
|
|
547
|
+
.memory-confirm p { line-height:1.8; }
|
|
548
|
+
.memory-confirm .section-actions { justify-content:flex-end; }
|
|
549
|
+
@media(max-width:460px) { .flow-column:last-child .flow-column-title { padding-left:4px; } }
|
|
550
|
+
|
|
551
|
+
.memory-model-value .hint { margin:0; }
|
|
552
|
+
.memory-model-value { min-width:0;max-width:100%; }
|
|
553
|
+
.memory-model-value strong { min-width:0;overflow-wrap:anywhere; }
|
package/src/dashboard/ui.js
CHANGED
|
@@ -186,12 +186,14 @@ function applyModels(data, { changed }) {
|
|
|
186
186
|
for (const model of data.models) {
|
|
187
187
|
const clients = (model.clients || []).map(id => ({ codex: "Codex App", claude_app: "Claude App", claude_code: "Claude Code" })[id] || id).join(" / ") || "—";
|
|
188
188
|
const row = tableRow([model.id, clients, ""]);row.children[0].className = "model-name";
|
|
189
|
+
if (model.vendor && model.vendor !== "Unknown") { const maker = document.createElement("span");maker.className = "model-maker";maker.textContent = model.vendor;row.children[0].append(maker); }
|
|
189
190
|
const details = document.createElement("details"), summary = document.createElement("summary"), fields = document.createElement("dl");
|
|
190
191
|
details.dataset.model = model.id;details.open = expanded.has(model.id);fields.className = "failure-detail";
|
|
191
192
|
localize(summary, "model_details");details.append(summary, fields);
|
|
192
|
-
for (const [key, value, translated] of [["vendor", model.vendor
|
|
193
|
+
for (const [key, value, translated] of [["vendor", model.vendor && model.vendor !== "Unknown" ? model.vendor : phrase("cap_unknown")], ["model_owner", model.owned_by], ["api", model.endpoints.join(" / ") || "—"],
|
|
193
194
|
["reasoning", model.reasoning_efforts?.join(" / ") || "—"], ["state", model.preview ? "preview" : model.state || "listed", true],
|
|
194
195
|
["model_window", number(model.context_window)]]) {
|
|
196
|
+
if (value === undefined) continue;
|
|
195
197
|
const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);
|
|
196
198
|
if (translated) localize(detail, value);else detail.textContent = value;
|
|
197
199
|
fields.append(term, detail);
|
|
@@ -315,7 +317,8 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
|
|
|
315
317
|
["network_failure_stage", network ? phrase(`network_stage_${network.stage}`) : null],
|
|
316
318
|
["network_cause_code", network?.cause_code], ["http_status", catalog?.http_status || diagnostic.http_status], ["last_success", catalog?.last_success_at], ["upstream_request_id", catalog?.request_id]]) {
|
|
317
319
|
if (value === null || value === undefined || value === "") continue;
|
|
318
|
-
|
|
320
|
+
if (value === undefined) continue;
|
|
321
|
+
const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);
|
|
319
322
|
if (value?.key) localize(detail, value.key, value.values);else detail.textContent = String(value).slice(0, 300);
|
|
320
323
|
fields.append(term, detail);
|
|
321
324
|
}
|
|
@@ -8,9 +8,9 @@ export function modelReasoningEfforts(model) {
|
|
|
8
8
|
return Array.isArray(values) ? [...new Set(values.filter(value => typeof value === "string" && /^[a-z][a-z0-9_-]{0,15}$/.test(value)))].slice(0, 16) : null;
|
|
9
9
|
}
|
|
10
10
|
|
|
11
|
-
export function publicModelCatalog(models, { clients = () => [], selectable = () => false } = {}) {
|
|
11
|
+
export function publicModelCatalog(models, { clients = () => [], selectable = () => false, maker = model => model.publisher || model.vendor || model.owned_by || "Unknown" } = {}) {
|
|
12
12
|
return models.slice(0, 1000).filter(model => typeof model?.id === "string").map(model => ({
|
|
13
|
-
id: model.id, vendor: model
|
|
13
|
+
id: model.id, vendor: maker(model), ...(model.owned_by ? { owned_by: model.owned_by } : {}),
|
|
14
14
|
endpoints: [["responses", ["/responses", "/v1/responses"]], ["chat", ["/chat/completions", "/v1/chat/completions"]],
|
|
15
15
|
["messages", ["/v1/messages"]]].filter(([, paths]) => paths.some(path => model.supported_endpoints?.includes(path))).map(([label]) => label),
|
|
16
16
|
preview: model.preview === true, selectable: selectable(model), clients: clients(model),
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
|
|
3
|
+
import { readBoundedResponseText } from "../http-transport.mjs";
|
|
4
|
+
|
|
5
|
+
// One API/key configuration owns these bounded observations and operations.
|
|
6
|
+
// Unknown capabilities share their first real count, not another inference.
|
|
7
|
+
export function createApiTokenCounter({ request, now = Date.now }) {
|
|
8
|
+
const flights = new Map(), capabilities = new Map(), shared = createAbortAwareSingleflight();let bytes = 0;
|
|
9
|
+
const missed = () => new Response(JSON.stringify({ type: "error", error: { type: "api_error", code: "ccdx_api_count_tokens_unavailable",
|
|
10
|
+
message: "This source's token-count endpoint returned HTTP 404. Message generation is separate." } }), { status: 404, headers: { "Content-Type": "application/json" } });
|
|
11
|
+
const observe = (scope, status) => { capabilities.delete(scope);capabilities.set(scope, { status, at: now() });while (capabilities.size > 128) capabilities.delete(capabilities.keys().next().value); };
|
|
12
|
+
return {
|
|
13
|
+
async count(body, options = {}) {
|
|
14
|
+
if (options.signal?.aborted) throw options.signal.reason;
|
|
15
|
+
const headers = Object.fromEntries(["anthropic-version", "anthropic-beta"].map(name => [name, options.headers?.[name] || ""]));
|
|
16
|
+
const scope = createHash("sha256").update(JSON.stringify([body.model, headers])).digest("hex"), known = capabilities.get(scope), at = now();
|
|
17
|
+
if (known?.status === 404 && at >= known.at && at - known.at < 60000) { options.onCountObservation?.({ cached: true });return missed(); }
|
|
18
|
+
if (known?.status === 404) capabilities.delete(scope);
|
|
19
|
+
const serialized = JSON.stringify(body), size = Buffer.byteLength(serialized), hash = size <= 1024 * 1024 ? createHash("sha256").update(scope).update(serialized).digest("hex") : null;
|
|
20
|
+
const identity = hash || {};
|
|
21
|
+
async function run(probe) {
|
|
22
|
+
const key = probe ? "probe:" + scope : "body:" + hash, waiter = { start: options.onUpstreamStart, observe: options.onCountObservation, signal: options.signal, identity };
|
|
23
|
+
let flight = flights.get(key);
|
|
24
|
+
if (flight && [...flight.waiters].every(item => item.signal?.aborted)) { flights.delete(key);bytes -= flight.bytes;flight = null; }
|
|
25
|
+
const joinable = (probe || hash !== null) && (Boolean(flight) || flights.size < 16 && (probe || bytes + size <= 4 * 1024 * 1024));
|
|
26
|
+
if (!flight || !joinable) {
|
|
27
|
+
flight = { key: {}, identity, bytes: probe ? 0 : size, waiters: new Set(), started: false, shared: false };
|
|
28
|
+
if (joinable) { flights.set(key, flight);bytes += flight.bytes; }
|
|
29
|
+
} else if (flight.identity === identity) flight.shared = true;
|
|
30
|
+
flight.waiters.add(waiter);
|
|
31
|
+
const start = item => {
|
|
32
|
+
item.start?.();
|
|
33
|
+
item.observe?.(item.identity === flight.identity ? { upstream: true, shared: flight.shared } : { waited: true });
|
|
34
|
+
};
|
|
35
|
+
if (flight.started) start(waiter);
|
|
36
|
+
const task = 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) if (!item.signal?.aborted) start(item); } });
|
|
41
|
+
if (signal?.aborted) { await response.body?.cancel();throw signal.reason; }
|
|
42
|
+
if (response.status === 404) {
|
|
43
|
+
await response.body?.cancel();observe(scope, 404);const result = missed();
|
|
44
|
+
return { identity: flight.identity, status: 404, headers: [...result.headers], text: await result.text() };
|
|
45
|
+
}
|
|
46
|
+
const text = await readBoundedResponseText(response, { maxBytes: 64 * 1024, label: "API token count", signal });
|
|
47
|
+
if (response.ok) observe(scope, 200);
|
|
48
|
+
return { identity: flight.identity, status: response.status, headers: [...response.headers], text };
|
|
49
|
+
} finally { if (joinable && flights.get(key) === flight) { flights.delete(key);bytes -= flight.bytes; } }
|
|
50
|
+
};
|
|
51
|
+
try {
|
|
52
|
+
const result = joinable ? await shared.run(flight.key, task, { signal: options.signal }) : await task(options.signal);
|
|
53
|
+
if (result.identity !== identity) {
|
|
54
|
+
options.onCountObservation?.({ waited: true, ...(result.status === 404 ? { cached: true } : {}) });
|
|
55
|
+
if (result.status !== 404) return run(false);
|
|
56
|
+
} else options.onCountObservation?.({ shared: flight.shared });
|
|
57
|
+
return new Response(result.text || null, { status: result.status, headers: result.headers });
|
|
58
|
+
} finally {
|
|
59
|
+
flight.waiters.delete(waiter);
|
|
60
|
+
if (!flight.waiters.size && joinable && flights.get(key) === flight) { flights.delete(key);bytes -= flight.bytes; }
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return run(!capabilities.has(scope));
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
package/src/providers/api.mjs
CHANGED
|
@@ -12,18 +12,20 @@ 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";
|
|
18
|
+
import { apiModelDisplay } from "../api-model-display.mjs";
|
|
17
19
|
|
|
18
20
|
const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
|
|
19
21
|
export function apiCatalog(config, env = process.env) {
|
|
20
22
|
const revision = deploymentRevision(config, env);
|
|
21
23
|
return config.models.map(model => { const protocol_capabilities = Object.fromEntries(model.protocols.map(protocol => [protocol, resolveModelCapabilities(model, { revision, protocol })]));
|
|
22
|
-
const capability = protocol_capabilities[model.protocols.includes("messages") ? "messages" : model.protocols[0]];return ({ id: model.id, name: model.id,
|
|
24
|
+
const capability = protocol_capabilities[model.protocols.includes("messages") ? "messages" : model.protocols[0]];return ({ id: model.id, name: model.id,
|
|
23
25
|
supported_endpoints: model.protocols.map(api => paths[api]), model_picker_enabled: true, policy: { state: "enabled" },
|
|
24
26
|
capability, protocol_capabilities }); });
|
|
25
27
|
}
|
|
26
|
-
export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork } = {}) {
|
|
28
|
+
export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork, modelDisplay = () => ({}) } = {}) {
|
|
27
29
|
const catalog = apiCatalog(config, env);
|
|
28
30
|
const fingerprint = config.key_env ? createHash("sha256").update(env[config.key_env] || "").digest("hex") : "";
|
|
29
31
|
const generation = parseInt(createHash("sha256").update(JSON.stringify(config) + fingerprint).digest("hex").slice(0, 8), 16);
|
|
@@ -67,10 +69,15 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
67
69
|
const constrained = constrainModelRequest(body, capability, api);
|
|
68
70
|
if (constrained.body !== body) { body = constrained.body;options = { ...options, bodyText: undefined }; }
|
|
69
71
|
markRequestObservation({ capability_revision: capability?.revision, capability_constraints: constrained.applied.join(",") || "none" });
|
|
72
|
+
markRequestObservation({ context_window_tokens: capability?.values.context_window });
|
|
70
73
|
}
|
|
71
74
|
const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
|
|
72
75
|
if (serialized !== undefined) headers["Content-Length"] = String(Buffer.byteLength(serialized));
|
|
73
76
|
options.onUpstreamStart?.();
|
|
77
|
+
if (body && options.observeUpstream !== false) {
|
|
78
|
+
markUpstreamStarted(body.stream === true);
|
|
79
|
+
if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: api === "messages" ? body.max_tokens : api === "chat" ? body.max_completion_tokens : body.max_output_tokens });
|
|
80
|
+
}
|
|
74
81
|
try {
|
|
75
82
|
const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
|
|
76
83
|
if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
|
|
@@ -91,6 +98,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
91
98
|
throw failure;
|
|
92
99
|
}
|
|
93
100
|
}
|
|
101
|
+
const counter = createApiTokenCounter({ request: (body, options) => request(config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens", body, options, "messages") });
|
|
94
102
|
const client = {
|
|
95
103
|
listModels: async () => ({ status: 200, body: JSON.stringify(registry.models) }),
|
|
96
104
|
getCachedModelEndpoints: id => catalog.find(model => model.id === id)?.supported_endpoints || null,
|
|
@@ -106,7 +114,8 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
106
114
|
chatCompletions(body, options = {}) { selected(body.model, "chat");return request(config.endpoints.chat, body, options, "chat"); },
|
|
107
115
|
messages(body, options = {}) {
|
|
108
116
|
const model = selected(body.model, "messages");
|
|
109
|
-
|
|
117
|
+
const outgoing = model.id === body.model ? body : { ...body, model: model.id };
|
|
118
|
+
return options.countTokens ? counter.count(outgoing, options) : request(config.endpoints.messages, outgoing, options, "messages");
|
|
110
119
|
},
|
|
111
120
|
};
|
|
112
121
|
return {
|
|
@@ -115,20 +124,25 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
115
124
|
.map(model => ({ ...model, capability: model.protocol_capabilities[family === "claude" ? "messages" : "responses"] })),
|
|
116
125
|
catalog: () => catalog,
|
|
117
126
|
publicCatalog(allowed = []) { return { source: "configured", checkedAt: config.checked_at || null, upstreamHost: new URL(config.base_url).hostname,
|
|
118
|
-
advertised: catalog.length, models: publicModelCatalog(catalog
|
|
127
|
+
advertised: catalog.length, models: publicModelCatalog(catalog.map(model => ({ ...model, ...modelDisplay(model.id) })), { maker: model => model.publisher || model.vendor || null,
|
|
128
|
+
selectable: model => allowed.some(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)),
|
|
119
129
|
clients: model => allowed.filter(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)) }).map(model => ({ ...model,
|
|
120
130
|
capability: catalog.find(entry => entry.id === model.id)?.capability, auto_review_efforts: [...(catalog.find(entry => entry.id === model.id)?.protocol_capabilities.responses?.values.reasoning_efforts || [])] })) }; },
|
|
121
131
|
async discover({ signal } = {}) {
|
|
122
132
|
const models = [], ids = new Set(), checked_at = new Date().toISOString();let url = modelsUrl, bytes = 0;
|
|
123
133
|
for (let page = 0; page < 25; page++) {
|
|
124
134
|
const response = await request(url, undefined, { signal }, config.endpoints.responses ? "responses" : "messages");
|
|
125
|
-
if (!response.ok) {
|
|
135
|
+
if (!response.ok) {
|
|
136
|
+
await response.body?.cancel();const error = accessError(`ccdx_api_catalog_http_${response.status}`, response.status === 401 || response.status === 403 ? response.status : 502);
|
|
137
|
+
const retry = response.headers.get("retry-after"), delay = /^\d{1,8}$/.test(retry || "") ? Number(retry) * 1000 : Date.parse(retry) - Date.now();
|
|
138
|
+
if (Number.isFinite(delay) && delay > 0) error.retryAfterMs = Math.min(delay, 86400000);throw error;
|
|
139
|
+
}
|
|
126
140
|
const text = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES - bytes, label: "API model catalog", signal });bytes += Buffer.byteLength(text);
|
|
127
141
|
let value;try { value = JSON.parse(text); } catch { throw accessError("ccdx_api_catalog_invalid", 502); }
|
|
128
142
|
if (!Array.isArray(value.data) || models.length + value.data.length > 500) throw accessError("ccdx_api_catalog_invalid", 502);
|
|
129
143
|
for (const model of value.data) { if (!model || typeof model.id !== "string" || !/^[\w][\w./:@+-]{0,159}$/.test(model.id) || model.id.includes("..") || model.id.includes("//") || ids.has(model.id)) throw accessError("ccdx_api_catalog_invalid", 502);ids.add(model.id); }
|
|
130
144
|
// A catalog listing is not evidence that every model supports every API.
|
|
131
|
-
models.push(...value.data.map(model => ({ id: model.id, metadata: apiModelMetadata(model, { checked_at, deployment: deploymentRevision(config, env) }), protocols: Array.isArray(model.supported_endpoints)
|
|
145
|
+
models.push(...value.data.map(model => ({ id: model.id, display: apiModelDisplay(model), metadata: apiModelMetadata(model, { checked_at, deployment: deploymentRevision(config, env) }), protocols: Array.isArray(model.supported_endpoints)
|
|
132
146
|
? Object.entries(paths).filter(([, endpoint]) => model.supported_endpoints.includes(endpoint) || model.supported_endpoints.includes(endpoint.slice(3))).map(([api]) => api).filter(api => config.endpoints[api]) : [] })));
|
|
133
147
|
if (value.has_more !== true) return models;
|
|
134
148
|
// Follow only the native cursor on the configured origin, never an
|
package/src/providers/m365.mjs
CHANGED
|
@@ -118,7 +118,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
118
118
|
const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
|
|
119
119
|
if (serialized !== undefined) requestHeaders["Content-Length"] = String(Buffer.byteLength(serialized));
|
|
120
120
|
options.onUpstreamStart?.();
|
|
121
|
-
if (body) markUpstreamStarted(body.stream === true);
|
|
121
|
+
if (body) { markUpstreamStarted(body.stream === true);if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: endpoint.includes("messages") ? body.max_tokens : body.max_output_tokens }); }
|
|
122
122
|
try {
|
|
123
123
|
const send = fetchImpl || await transport(options.signal);
|
|
124
124
|
const response = await send(`${M365_API_BASE}${endpoint}`, { method: body ? "POST" : "GET", headers: requestHeaders,
|
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
|
+
}
|
|
@@ -2,6 +2,7 @@ import { terminalCell } from "./terminal-text.mjs";
|
|
|
2
2
|
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
3
3
|
import { currentRequestContext } from "./request-context.mjs";
|
|
4
4
|
import { isProviderId } from "./provider-metadata.mjs";
|
|
5
|
+
import { transportErrorDetails } from "./operation-error.mjs";
|
|
5
6
|
|
|
6
7
|
const DEFAULT_RECENT_FAILURES = 10;
|
|
7
8
|
|
|
@@ -129,6 +130,7 @@ export function requestOptionsEvidence(body) {
|
|
|
129
130
|
if (["auto", "default", "flex", "priority", "scale"].includes(body.service_tier)) result.service_tier = body.service_tier;
|
|
130
131
|
if (["text", "json_object", "json_schema"].includes(body.text?.format?.type)) result.output_format = body.text.format.type;
|
|
131
132
|
if (Number.isSafeInteger(body.max_output_tokens) && body.max_output_tokens >= 0) result.max_output_tokens = body.max_output_tokens;
|
|
133
|
+
if (Number.isSafeInteger(body.max_tokens) && body.max_tokens >= 0) result.max_tokens = body.max_tokens;
|
|
132
134
|
if (Array.isArray(body.tools)) result.tools = body.tools.length;
|
|
133
135
|
if (Array.isArray(body.input)) result.input_items = body.input.length;
|
|
134
136
|
return result;
|
|
@@ -138,26 +140,48 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
|
|
|
138
140
|
const all = createResponseFailureDiagnostics({ maxEntries, now });
|
|
139
141
|
const actionable = createResponseFailureDiagnostics({ maxEntries, now });
|
|
140
142
|
const protocol = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
141
|
-
const
|
|
143
|
+
const capability = createResponseFailureDiagnostics({ maxEntries: 20, now });
|
|
144
|
+
const routes = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
145
|
+
const counts = { inference: 0, capability: 0, protocol: 0, route: 0, other: 0 };
|
|
142
146
|
return {
|
|
143
147
|
record(details) {
|
|
144
148
|
all.record(details);
|
|
145
|
-
const
|
|
149
|
+
const accessNotice = details.reason === "ccdx_model_not_selected" || details.reason === "ccdx_client_source_disabled";
|
|
150
|
+
const category = accessNotice || details.route === "messages_count_tokens" ? "capability"
|
|
151
|
+
: ["responses", "responses_compact", "messages"].includes(details.route) ? "inference"
|
|
146
152
|
: details.route === "image_mcp" && details.http_status === 405 ? "protocol"
|
|
147
153
|
: details.route === "not_found" ? "route" : "other";
|
|
148
154
|
counts[category]++;
|
|
149
|
-
if (category === "inference" || category === "other") actionable.record(details);
|
|
155
|
+
if ((category === "inference" || category === "other") && !accessNotice) actionable.record(details);
|
|
156
|
+
if (category === "capability") {
|
|
157
|
+
capability.record(details);
|
|
158
|
+
if (!accessNotice && ![404, 405, 501].includes(details.http_status)) actionable.record(details);
|
|
159
|
+
}
|
|
150
160
|
if (category === "protocol") protocol.record(details);
|
|
161
|
+
if (category === "route") routes.record(details);
|
|
151
162
|
},
|
|
152
163
|
snapshot() { return { ...all.snapshot(), by_category: { ...counts },
|
|
153
|
-
actionable_recent: actionable.snapshot().recent,
|
|
164
|
+
actionable_recent: actionable.snapshot().recent, capability_recent: capability.snapshot().recent,
|
|
165
|
+
protocol_recent: protocol.snapshot().recent, route_recent: routes.snapshot().recent }; },
|
|
154
166
|
};
|
|
155
167
|
}
|
|
156
168
|
|
|
157
169
|
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
|
|
170
|
+
error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
|
|
171
|
+
application, reason, capability_cached, shared_upstream, transport }) {
|
|
172
|
+
if (!reason && code === "ccdx_client_source_disabled" && upstream_attempts === 0 && origin !== "upstream_http") {
|
|
173
|
+
reason = code;origin = "client_validation";
|
|
174
|
+
}
|
|
175
|
+
const reasons = { ccdx_model_not_selected: "This model is not selected for this app.",
|
|
176
|
+
ccdx_model_ambiguous: "This model name matches multiple sources. Select its source-specific entry.",
|
|
177
|
+
ccdx_model_catalog_unavailable: "The selected model is not currently available in its source catalog.",
|
|
178
|
+
ccdx_client_source_disabled: "This app or its model source is turned off." };
|
|
179
|
+
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."
|
|
180
|
+
: code === "ccdx_api_network_unavailable" ? "Connection to the model source failed."
|
|
181
|
+
: origin === "client_validation" ? "The request was rejected locally before an upstream call."
|
|
182
|
+
: error_body === "empty" ? "Upstream returned no error details." : "HTTP request failed; original response was preserved.");
|
|
159
183
|
const details = responseFailureDetails({ model, error: { code: typeof code === "string" && /^[a-z\d_.:-]{1,80}$/i.test(code) ? code : `http_${statusCode}`,
|
|
160
|
-
message
|
|
184
|
+
message } }, "http.error", { headers, provider });
|
|
161
185
|
return { ...details, request_id: requestId, http_status: statusCode, route,
|
|
162
186
|
origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true,
|
|
163
187
|
...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}), ...(parameter ? { parameter } : {}),
|
|
@@ -166,5 +190,9 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
|
|
|
166
190
|
...(request_options ? { request_options } : {}),
|
|
167
191
|
...(attempt_timings ? { attempt_timings } : {}),
|
|
168
192
|
...(requested_model ? { requested_model, request_kind: requested_model === "codex-auto-review" ? "auto_review" : "unknown" } : {}),
|
|
193
|
+
...(["codex_app", "codex_cli", "codex", "claude_app", "claude_code", "claude", "api"].includes(application) ? { application } : {}),
|
|
194
|
+
...(Object.hasOwn(reasons, reason) ? { reason } : {}),
|
|
195
|
+
...(capability_cached === true ? { capability_cached: true } : {}), ...(shared_upstream === true ? { shared_upstream: true } : {}),
|
|
196
|
+
...(transport ? { transport: transportErrorDetails({ transport }) } : {}),
|
|
169
197
|
...(Number.isSafeInteger(upstream_attempts) ? { upstream_attempts } : {}) };
|
|
170
198
|
}
|
|
@@ -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,8 @@ 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);
|
|
211
|
+
markRequestObservation({ max_output_tokens_requested: parsed?.max_output_tokens });
|
|
209
212
|
const selectedProvider = options.resolveProvider?.(parsed, req);
|
|
210
213
|
if (selectedProvider) {
|
|
211
214
|
provider = selectedProvider;modelRegistry = provider.registry;
|
|
@@ -489,6 +492,8 @@ export function createResponsesCompactHandler(options) {
|
|
|
489
492
|
releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
|
|
490
493
|
abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
|
|
491
494
|
const parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
|
|
495
|
+
observeRequestedModel(parsed);
|
|
496
|
+
markRequestObservation({ max_output_tokens_requested: parsed?.max_output_tokens });
|
|
492
497
|
const selectedProvider = options.resolveProvider?.(parsed, req);
|
|
493
498
|
if (selectedProvider) {
|
|
494
499
|
provider = selectedProvider;modelRegistry = provider.registry;
|
|
@@ -249,7 +249,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
249
249
|
let headersAt = null;
|
|
250
250
|
let lastActivityAt = null;
|
|
251
251
|
let terminalAt = null;
|
|
252
|
-
const context = { payload_bytes: null, images: null, input_tokens: null, context_window_tokens: null };
|
|
252
|
+
const context = { payload_bytes: null, images: null, input_tokens: null, context_window_tokens: null, output_tokens: null, max_output_tokens_requested: null, max_output_tokens_sent: null };
|
|
253
|
+
let stopReason = null;
|
|
253
254
|
const elapsed = (time) => time === null ? null : Number(Math.max(0, time - requestStartedAt).toFixed(1));
|
|
254
255
|
if (activeRequests.size < MAX_ACTIVE_REQUESTS) activeRequests.set(activeId, () => ({
|
|
255
256
|
request_id: safeRequestId, application: client, route: routeName, provider, model, phase,
|
|
@@ -337,19 +338,20 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
337
338
|
setErrorOrigin(value) {
|
|
338
339
|
if (TERMINAL_ORIGINS.has(value)) errorOrigin = value;
|
|
339
340
|
},
|
|
340
|
-
terminal(outcome, { model: terminalModel, origin, reason } = {}) {
|
|
341
|
+
terminal(outcome, { model: terminalModel, origin, reason, stopReason: stopped } = {}) {
|
|
341
342
|
if (finished || terminalOutcome || !TERMINAL_OUTCOMES.includes(outcome)) return;
|
|
342
343
|
terminalOutcome = outcome;
|
|
343
344
|
terminalAt = now();
|
|
344
345
|
if (terminalModel !== undefined) model = modelLabel(terminalModel);
|
|
345
346
|
if (TERMINAL_ORIGINS.has(origin)) terminalOrigin = origin;
|
|
346
347
|
if (outcome === "incomplete") incompleteReason = INCOMPLETE_REASONS.has(reason) ? reason : "other";
|
|
348
|
+
if (["end_turn", "max_tokens", "tool_use", "stop_sequence", "pause_turn", "refusal", "model_context_window_exceeded"].includes(stopped)) stopReason = stopped;
|
|
347
349
|
if (outcome !== "completed") failed = true;
|
|
348
350
|
},
|
|
349
351
|
fail() {
|
|
350
352
|
failed = true;
|
|
351
353
|
},
|
|
352
|
-
finish({ failed: finishFailed = false, aborted = false, statusCode = 0 } = {}) {
|
|
354
|
+
finish({ failed: finishFailed = false, aborted = false, statusCode = 0, rejectionReason } = {}) {
|
|
353
355
|
if (finished) return;
|
|
354
356
|
if (!sourceStats) assignProvider("unknown");
|
|
355
357
|
finished = true;
|
|
@@ -381,6 +383,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
381
383
|
recentRequests.push({
|
|
382
384
|
request_id: safeRequestId, application: client,
|
|
383
385
|
at, route: routeName, model, outcome, origin, phase,
|
|
386
|
+
...(["ccdx_model_not_selected", "ccdx_client_source_disabled"].includes(rejectionReason) ? { rejection_reason: rejectionReason } : {}),
|
|
387
|
+
...(stopReason ? { stop_reason: stopReason } : {}),
|
|
384
388
|
...(provider ? { provider } : {}),
|
|
385
389
|
empty_stream_completion: emptyStreamCompletion,
|
|
386
390
|
failed: failed || aborted || (terminalOutcome !== null && terminalOutcome !== "completed"),
|
|
@@ -458,6 +462,8 @@ export async function measureRequestStageAsync(stage, operation) {
|
|
|
458
462
|
}
|
|
459
463
|
|
|
460
464
|
export function markUpstreamStarted(streaming = true) {
|
|
465
|
+
const context = currentRequestContext();
|
|
466
|
+
if (context) context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;
|
|
461
467
|
tracker()?.upstreamStarted(streaming);
|
|
462
468
|
}
|
|
463
469
|
|
|
@@ -489,7 +495,7 @@ export function markResponseModel(model, { requestedModel, configuredModel = fal
|
|
|
489
495
|
const context = currentRequestContext();
|
|
490
496
|
if (context) {
|
|
491
497
|
context.model = model;
|
|
492
|
-
if (requestedModel !== undefined) context.requestedModel = modelLabel(requestedModel);
|
|
498
|
+
if (requestedModel !== undefined && context.requestedModel === undefined) context.requestedModel = modelLabel(requestedModel);
|
|
493
499
|
}
|
|
494
500
|
tracker()?.setModel?.(model, { configured: configuredModel });
|
|
495
501
|
}
|