codex-copilot-dx 1.2.23 → 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 +32 -0
- package/docs/REFERENCE.md +74 -7
- package/package.json +1 -1
- package/src/adapter.mjs +2 -1
- package/src/api-catalog-refresh.mjs +2 -2
- package/src/api-model-display.mjs +47 -0
- package/src/claude-gateway.mjs +18 -9
- package/src/cli-status.mjs +1 -1
- package/src/codex-memory-model.mjs +64 -0
- package/src/codex-memory-probe.mjs +25 -0
- package/src/connection-runtime.mjs +22 -8
- package/src/dashboard/connections.js +61 -7
- package/src/dashboard/flow.js +3 -8
- package/src/dashboard/index.html +5 -0
- package/src/dashboard/language.js +31 -2
- package/src/dashboard/status.js +14 -7
- package/src/dashboard/ui.css +29 -6
- package/src/dashboard/ui.js +5 -2
- package/src/provider-metadata.mjs +2 -2
- package/src/providers/api-token-count.mjs +52 -47
- package/src/providers/api.mjs +11 -5
- package/src/providers/m365.mjs +1 -1
- package/src/response-failures.mjs +13 -5
- package/src/responses-handler.mjs +2 -0
- package/src/stream-performance.mjs +7 -3
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const words = (node, key, args) => globalThis.ccdxLanguage.set(node, key, args), format = key => globalThis.ccdxLanguage.format(key);
|
|
4
4
|
let data = null, editing = null, editingClient = null, disabling = null, models = [], selectedModels = new Set(), busy = false, generation = 0;
|
|
5
5
|
let claudeClient = "claude_app", bindingSelection = new Set(), bindingDefault = null, bindingDirty = false;
|
|
6
|
+
let memoryAction = null, memoryOrigin = null;
|
|
6
7
|
const drafts = new Map();let editorOrigin = null, discovery = null, desiredSource = null;
|
|
7
8
|
const apiForm = el("connection-api-form"), clientForm = el("connection-client-form");
|
|
8
9
|
const node = (tag, text, className) => { const item = document.createElement(tag);if (text !== undefined) item.textContent = text;if (className) item.className = className;return item; };
|
|
@@ -112,6 +113,12 @@
|
|
|
112
113
|
const protocol = choice(model.protocols.map(id => ({ id, name: id === "messages" ? "Messages" : id === "responses" ? "Responses" : "Chat" })), model.protocols.includes("messages") ? "messages" : model.protocols[0], false);
|
|
113
114
|
protocol.setAttribute("aria-label", format("cap_api"));detail.append(protocol);
|
|
114
115
|
const status = node("p", undefined, "hint"), table = node("table"), body = node("tbody");table.append(body);detail.append(status, table);
|
|
116
|
+
const maker = model.display || source(editing)?.model_display?.[model.id] || {};
|
|
117
|
+
const identity = node("dl", undefined, "model-identity");
|
|
118
|
+
for (const [label, value] of [["vendor", maker.publisher || maker.vendor || format("cap_unknown")], ["model_owner", maker.owned_by]]) {
|
|
119
|
+
if (!value) continue;const term = node("dt");words(term, label);identity.append(term, node("dd", value));
|
|
120
|
+
}
|
|
121
|
+
detail.insertBefore(identity, protocol);
|
|
115
122
|
const advanced = node("details"), summary = node("summary");words(summary, "cap_manual");advanced.append(summary);detail.append(advanced);
|
|
116
123
|
const note = node("p", undefined, "hint");words(note, "cap_metadata_scope");advanced.append(note);
|
|
117
124
|
const fields = node("div", undefined, "connection-fields");
|
|
@@ -177,6 +184,8 @@
|
|
|
177
184
|
tr.dataset.model = model.id;
|
|
178
185
|
const selection = check("selected-model", model.id, selectedModels.has(model.id), model.id);
|
|
179
186
|
selection.firstChild.addEventListener("change", e => { if (e.target.checked) selectedModels.add(model.id);else selectedModels.delete(model.id); });name.append(selection);
|
|
187
|
+
const maker = model.display || source(editing)?.model_display?.[model.id];
|
|
188
|
+
if (maker?.publisher || maker?.vendor) name.append(node("span", maker.publisher || maker.vendor, "model-maker"));
|
|
180
189
|
for (const protocol of ["messages", "responses", "chat"]) {
|
|
181
190
|
const label = check("model-api", protocol, model.protocols.includes(protocol), protocol === "chat" ? "Chat" : protocol === "messages" ? "Messages" : "Responses");
|
|
182
191
|
label.firstChild.disabled = !apiForm.querySelector(`[name="protocol"][value="${protocol}"]`).checked;
|
|
@@ -212,7 +221,7 @@
|
|
|
212
221
|
apiForm.elements.key_env.addEventListener("input", keyMode);
|
|
213
222
|
apiForm.addEventListener("submit", e => {
|
|
214
223
|
e.preventDefault();if (busy || !apiForm.reportValidity()) return;
|
|
215
|
-
const chosenModels = models.filter(model => selectedModels.has(model.id));
|
|
224
|
+
const chosenModels = models.filter(model => selectedModels.has(model.id)).map(({ display, ...model }) => model);
|
|
216
225
|
const invalid = chosenModels.find(model => !model.protocols.length);
|
|
217
226
|
if (invalid) {
|
|
218
227
|
message("api_model_protocol_required", { model: invalid.id });
|
|
@@ -242,11 +251,43 @@
|
|
|
242
251
|
try {
|
|
243
252
|
const result = await api({ operation: "discover", id: read.id }, read.controller.signal);if (discovery !== read || editing !== read.id) return;
|
|
244
253
|
data = result;
|
|
245
|
-
const known = new Map(models.map(model => [model.id, model]));for (const model of result.discovered || []) { const previous = known.get(model.id);known.set(model.id, previous ? { ...previous, ...(model.metadata ? { metadata: model.metadata } : {}) } : model); }
|
|
254
|
+
const known = new Map(models.map(model => [model.id, model]));for (const model of result.discovered || []) { const previous = known.get(model.id);known.set(model.id, previous ? { ...previous, ...(model.display ? { display: model.display } : {}), ...(model.metadata ? { metadata: model.metadata } : {}) } : model); }
|
|
246
255
|
models = [...known.values()].slice(0, 500);modelRows();message("api_models_read");
|
|
247
256
|
} catch (error) { if (discovery === read) message(error.message); }
|
|
248
257
|
finally { if (discovery === read) { discovery = null;trigger.disabled = false;trigger.removeAttribute("aria-busy");words(trigger, "api_read_models");el("connection-discover-cancel").hidden = true; } }
|
|
249
258
|
});
|
|
259
|
+
function memoryMatches(item) {
|
|
260
|
+
const model = client("codex")?.memory_model?.model;
|
|
261
|
+
return Boolean(model && [item.id, item.model, item.route_id, item.public_id].includes(model));
|
|
262
|
+
}
|
|
263
|
+
function memoryRender() {
|
|
264
|
+
const area = el("connection-memory-model");if (!area || !data) return;
|
|
265
|
+
area.hidden = editingClient !== "codex";if (area.hidden) return;
|
|
266
|
+
const c = client("codex"), dep = c.memory_model || {};
|
|
267
|
+
el("connection-memory-name").textContent = dep.model || format("memory_not_detected");
|
|
268
|
+
words(el("connection-memory-basis"), dep.model ? `memory_basis_${dep.basis}` : "");
|
|
269
|
+
const selected = (c.deployments || c.model_plan?.models || []).some(memoryMatches);
|
|
270
|
+
const draft = dep.model && [...bindingSelection].some(key => {
|
|
271
|
+
const [source, id] = key.split("\0");return memoryMatches({ id, route_id: c.model_plan?.available?.find(x => x.source === source && x.id === id)?.route_id });
|
|
272
|
+
});
|
|
273
|
+
const pending = bindingDirty && Boolean(draft) !== selected;
|
|
274
|
+
const label = !dep.model ? "memory_not_detected" : dep.enabled === false ? "memory_generation_off" : pending ? draft ? "memory_pending_on" : "memory_pending_off" : selected ? "memory_model_on" : "memory_model_off";
|
|
275
|
+
const state = el("connection-memory-state");state.hidden = !dep.model;
|
|
276
|
+
if (globalThis.ccdxIcons) globalThis.ccdxIcons.set(state, label, dep.enabled === false ? "unavailable" : !selected || pending && !draft ? "warning" : "ok");else words(state, label);
|
|
277
|
+
const warning = el("connection-memory-warning");warning.hidden = !dep.model || dep.enabled === false || selected && !pending;
|
|
278
|
+
words(warning, selected && pending && !draft ? "memory_pending_warning" : "memory_off_warning");
|
|
279
|
+
}
|
|
280
|
+
function confirmMemory(action) {
|
|
281
|
+
memoryAction = action;memoryOrigin = document.activeElement;
|
|
282
|
+
el("connection-memory-confirm").showModal();el("connection-memory-keep").focus();
|
|
283
|
+
}
|
|
284
|
+
function closeMemory(confirm) {
|
|
285
|
+
const action = memoryAction;memoryAction = null;el("connection-memory-confirm").close();
|
|
286
|
+
if (confirm) action?.();else if (memoryOrigin?.isConnected) memoryOrigin.focus();
|
|
287
|
+
}
|
|
288
|
+
el("connection-memory-keep").addEventListener("click", () => closeMemory(false));
|
|
289
|
+
el("connection-memory-close").addEventListener("click", () => closeMemory(true));
|
|
290
|
+
el("connection-memory-confirm").addEventListener("cancel", () => { memoryAction = null; });
|
|
250
291
|
const bindingKey = (source, model) => source + "\0" + model;
|
|
251
292
|
const routeId = item => item.route_id || item.public_id;
|
|
252
293
|
function rememberDraft() {
|
|
@@ -271,6 +312,7 @@
|
|
|
271
312
|
bindingRows(document.activeElement?.name === "binding-model" ? { kind: "selection", key: document.activeElement.value } : document.activeElement?.dataset.binding ? { kind: "default", key: document.activeElement.dataset.binding } : null);words(el("connection-client-title"), "cap_visible_model");list();
|
|
272
313
|
}
|
|
273
314
|
function bindingRows(focus) {
|
|
315
|
+
memoryRender();
|
|
274
316
|
el("connection-client-cancel").disabled = !bindingDirty;
|
|
275
317
|
const body = el("connection-bindings"), c = client(editingClient);body.replaceChildren();
|
|
276
318
|
const available = c.model_plan?.available || [], availableKeys = new Set(available.map(item => bindingKey(item.source, item.id)));
|
|
@@ -279,10 +321,16 @@
|
|
|
279
321
|
const key = bindingKey(item.source, item.id), row = node("tr"), name = node("td"), capability = item.capability?.values || {};
|
|
280
322
|
const selection = check("binding-model", key, bindingSelection.has(key), item.id);
|
|
281
323
|
selection.firstChild.addEventListener("change", event => {
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
324
|
+
const checked = event.target.checked;
|
|
325
|
+
const apply = () => {
|
|
326
|
+
bindingDirty = true;if (checked) { bindingSelection.add(key);bindingDefault ||= routeId(item); }
|
|
327
|
+
else { bindingSelection.delete(key);if (bindingDefault === routeId(item) || !bindingSelection.size) bindingDefault = null; }
|
|
328
|
+
rememberDraft();bindingRows({ kind: "selection", key });
|
|
329
|
+
};
|
|
330
|
+
if (!checked && editingClient === "codex" && client("codex").memory_model?.enabled !== false && memoryMatches(item)) { event.target.checked = true;confirmMemory(apply); }
|
|
331
|
+
else apply();
|
|
285
332
|
});name.append(selection);
|
|
333
|
+
if (editingClient === "codex" && memoryMatches(item)) { const badge = node("span", undefined, "memory-model-badge");words(badge, "memory_extract_role");name.append(badge); }
|
|
286
334
|
const action = button(bindingDefault === routeId(item) && bindingSelection.has(key) ? "cap_default" : "cap_set_default", () => { bindingDirty = true;bindingSelection.add(key);bindingDefault = routeId(item);rememberDraft();bindingRows({ kind: "default", key }); });
|
|
287
335
|
action.setAttribute("aria-pressed", String(bindingDefault === routeId(item) && bindingSelection.has(key)));
|
|
288
336
|
action.dataset.binding = key;action.disabled = Boolean(item.unavailable);action.setAttribute("aria-label", item.id + " · " + format(bindingDefault === routeId(item) ? "cap_default" : "cap_set_default"));
|
|
@@ -313,7 +361,11 @@
|
|
|
313
361
|
}
|
|
314
362
|
clientForm.addEventListener("submit", event => { event.preventDefault();void change(bindingInput("client")); });
|
|
315
363
|
el("connection-sync-preview").addEventListener("click", () => void change(bindingInput("preview_client"), result => syncPreview(result.preview)));
|
|
316
|
-
function disableSource(provider) {
|
|
364
|
+
function disableSource(provider, confirmed = false) {
|
|
365
|
+
const c = client("codex");
|
|
366
|
+
if (!confirmed && c?.enabled && c.memory_model?.enabled !== false && c.model_plan?.models.some(item => item.source === provider.id && memoryMatches(item))) {
|
|
367
|
+
confirmMemory(() => disableSource(provider, true));return;
|
|
368
|
+
}
|
|
317
369
|
const affected = data.clients.filter(c => c.enabled && c.source === provider.id);
|
|
318
370
|
if (!affected.length) { void change({ operation: "provider", id: provider.id, enabled: false });return; }
|
|
319
371
|
disabling = provider.id;panels("disable");const area = el("connection-replacements");area.replaceChildren();
|
|
@@ -323,12 +375,14 @@
|
|
|
323
375
|
replacements: Object.fromEntries([...el("connection-replacements").querySelectorAll("select")].map(select => [select.name, select.value || null])) }); });
|
|
324
376
|
el("connection-add").addEventListener("click", () => { if (data) editApi(); });
|
|
325
377
|
for (const id of ["connection-cancel", "connection-disable-cancel"]) el(id).addEventListener("click", () => { panels();(editorOrigin?.isConnected ? editorOrigin : el("connection-source-list").querySelector("button") || el("connection-add")).focus(); });
|
|
378
|
+
el("refresh").addEventListener("click", () => { if (["#models", "#codex", "#claude"].includes(location.hash)) void load(); });
|
|
326
379
|
window.addEventListener("hashchange", () => { apiForm.elements.key.value = "";mountClient();if (["#models", "#claude", "#codex"].includes(location.hash)) void load(); });
|
|
327
380
|
window.addEventListener("ccdx:choose-source", event => { if (typeof event.detail?.id === "string" && providerEntries.some(p => p.id === event.detail.id)) chooseProvider(event.detail.id); });
|
|
328
381
|
window.addEventListener("ccdx:source-view", () => { if (data) list(); });
|
|
329
382
|
window.addEventListener("ccdx:providers", () => { if (desiredSource && providerEntries.some(p => p.id === desiredSource)) { const id = desiredSource;desiredSource = null;chooseProvider(id); }if (data) list(); });
|
|
330
383
|
new MutationObserver(() => { if (data) list(); }).observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] });
|
|
331
|
-
globalThis.ccdxConnections = { load,
|
|
384
|
+
globalThis.ccdxConnections = { load,
|
|
385
|
+
updateMemory(snapshot) { const c = snapshot?.clients?.find(c => c.id === "codex");if (data && c?.memory_model) { client("codex").memory_model = c.memory_model;memoryRender(); } }, editClient: id => { if (data && client(id)) { editClient(client(id)); } } };
|
|
332
386
|
for (const button of document.querySelectorAll("[data-client-access]")) button.addEventListener("click", () => globalThis.ccdxConnections.editClient(button.dataset.clientAccess));
|
|
333
387
|
void load();
|
|
334
388
|
})();
|
package/src/dashboard/flow.js
CHANGED
|
@@ -154,17 +154,12 @@
|
|
|
154
154
|
if (next === geometry && state === wireState) return;
|
|
155
155
|
if (next !== geometry) {
|
|
156
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 })
|
|
157
|
+
for (const edge of edges) wires.append(svg("path", { d: edge.d }));
|
|
158
158
|
}
|
|
159
159
|
wireState = state;
|
|
160
160
|
edges.forEach((edge, index) => {
|
|
161
|
-
const value = states[index], path = wires.children[index
|
|
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);
|
|
161
|
+
const value = states[index], path = wires.children[index];
|
|
162
|
+
path.setAttribute("class", `flow-wire${value.dim ? " flow-dim" : value.active ? " flow-live" : ""}${value.moving ? " flow-streaming" : value.active ? " flow-waiting" : ""}`);
|
|
168
163
|
});
|
|
169
164
|
}
|
|
170
165
|
function unavailable() { clearTimeout(expiry);expiry = null;fresh = false;deadline = 0;render(); }
|
package/src/dashboard/index.html
CHANGED
|
@@ -72,6 +72,10 @@
|
|
|
72
72
|
<section class="panel dashboard-section" id="connection-client-editor" hidden aria-labelledby="connection-client-title">
|
|
73
73
|
<div class="panel-heading"><h2 id="connection-client-title"></h2><span id="connection-draft-state" class="hint"></span></div>
|
|
74
74
|
<form id="connection-client-form">
|
|
75
|
+
<div id="connection-memory-model" hidden>
|
|
76
|
+
<div class="memory-model-row"><span data-i18n="memory_extract_model">Memory extraction model</span><div class="memory-model-value"><strong id="connection-memory-name">—</strong><span id="connection-memory-basis" class="hint"></span><span id="connection-memory-state"></span></div></div>
|
|
77
|
+
<p id="connection-memory-warning" class="memory-model-notice" role="status" hidden></p>
|
|
78
|
+
</div>
|
|
75
79
|
<p id="connection-default-note" class="hint" role="status" hidden></p>
|
|
76
80
|
<div class="table-wrap"><table class="binding-table"><thead><tr><th data-i18n="model">Model</th><th data-i18n="source">Source</th><th data-i18n="cap_context">Context</th><th data-i18n="cap_reasoning">Reasoning</th><th data-i18n="cap_default">Default</th></tr></thead><tbody id="connection-bindings"></tbody></table></div>
|
|
77
81
|
<div class="setting-row"><label for="connection-auto-sync" data-i18n="cap_auto_sync">Sync model settings</label><input id="connection-auto-sync" type="checkbox" role="switch" checked><span class="hint" data-i18n="cap_sync_scope">Preserves your manual settings.</span></div>
|
|
@@ -414,5 +418,6 @@
|
|
|
414
418
|
</main>
|
|
415
419
|
<footer data-i18n="local_only_visible_page_updates">THIS COMPUTER ONLY / UPDATES WHILE VISIBLE</footer>
|
|
416
420
|
</div>
|
|
421
|
+
<dialog id="connection-memory-confirm" class="memory-confirm" aria-labelledby="connection-memory-confirm-title"><h2 id="connection-memory-confirm-title" data-i18n="memory_close_title">Turn off the memory extraction model?</h2><p data-i18n="memory_close_body">Codex uses this model to extract new memories. Turning it off may prevent new memory generation.</p><p class="hint" data-i18n="memory_existing_kept">Existing memories will not be deleted.</p><div class="section-actions"><button type="button" id="connection-memory-keep" data-i18n="memory_keep_enabled">Keep enabled</button><button type="button" id="connection-memory-close" data-i18n="memory_close_anyway">Turn off anyway</button></div></dialog>
|
|
417
422
|
</body>
|
|
418
423
|
</html>
|
|
@@ -1,10 +1,37 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
const translations = {
|
|
3
|
+
"request_access_blocked": ["Access blocked", "请求已拦截"],
|
|
4
|
+
"not_applicable": ["Not applicable", "不适用"],
|
|
5
|
+
"model_owner": ["Model owner", "模型归属"],
|
|
6
|
+
"memory_extract_model": ["Memory extraction model", "记忆提取模型"],
|
|
7
|
+
"memory_extract_role": ["Memory extraction", "记忆提取"],
|
|
8
|
+
"memory_not_detected": ["Not detected", "未检测到"],
|
|
9
|
+
"memory_basis_configured": ["Configured in Codex", "Codex 已配置"],
|
|
10
|
+
"memory_basis_observed": ["Recently observed", "最近检测到"],
|
|
11
|
+
"memory_model_on": ["Enabled", "已启用"],
|
|
12
|
+
"memory_model_off": ["Not selected", "未选入"],
|
|
13
|
+
"memory_generation_off": ["Memory generation is off", "记忆生成已关闭"],
|
|
14
|
+
"memory_pending_on": ["Enabled after saving", "启用待保存"],
|
|
15
|
+
"memory_pending_off": ["Disabled after saving", "关闭待保存"],
|
|
16
|
+
"memory_off_warning": ["The memory extraction model is not enabled. New memory generation may be affected.", "记忆提取模型未启用,新记忆生成可能受影响。"],
|
|
17
|
+
"memory_pending_warning": ["Saving disables the memory extraction model. New memory generation may be affected.", "保存后将关闭记忆提取模型,新记忆生成可能受影响。"],
|
|
18
|
+
"memory_close_title": ["Turn off the memory extraction model?", "关闭记忆提取模型?"],
|
|
19
|
+
"memory_close_body": ["Codex uses this model to extract new memories. Turning it off may prevent new memory generation.", "Codex 使用此模型提取新记忆。关闭后,可能无法生成新记忆。"],
|
|
20
|
+
"memory_existing_kept": ["Existing memories will not be deleted.", "已有记忆不会因此删除。"],
|
|
21
|
+
"memory_keep_enabled": ["Keep enabled", "保留启用"],
|
|
22
|
+
"memory_close_anyway": ["Turn off anyway", "仍然关闭"],
|
|
23
|
+
"output_requested": ["Requested output budget", "请求输出预算"],
|
|
24
|
+
"output_sent": ["Forwarded output budget", "转发输出预算"],
|
|
25
|
+
"output_used": ["Returned output tokens", "返回输出用量"],
|
|
26
|
+
"stop_reason": ["Stop reason", "停止原因"],
|
|
27
|
+
"transport": ["Network details", "网络详情"],
|
|
28
|
+
"output_limit_reached": ["Output limit reached.", "本次生成达到输出上限。"],
|
|
29
|
+
"source_connection_failed": ["Connection to the model source failed.", "与模型来源的连接失败。"],
|
|
3
30
|
"issue_category": ["Issue category", "问题分类"],
|
|
4
31
|
"issue_replies": ["Reply issues", "回复问题"],
|
|
5
|
-
"issue_capabilities": ["
|
|
32
|
+
"issue_capabilities": ["Capabilities and access", "能力与访问"],
|
|
6
33
|
"issue_connections": ["Connections and paths", "连接与路径"],
|
|
7
|
-
"http_categories": ["Generation {inference} · Capabilities {capability} · Methods {protocol} · Paths {route} · Other {other}", "生成 {inference} ·
|
|
34
|
+
"http_categories": ["Generation {inference} · Capabilities/access {capability} · Methods {protocol} · Paths {route} · Other {other}", "生成 {inference} · 能力/访问 {capability} · 方法 {protocol} · 路径 {route} · 其他 {other}"],
|
|
8
35
|
"no_upstream_call": ["No upstream call", "未调用上游"],
|
|
9
36
|
"repeated_issue": ["{detail} · {count} occurrences", "{detail} · 出现 {count} 次"],
|
|
10
37
|
"reason": ["Reason", "具体原因"],
|
|
@@ -1183,6 +1210,8 @@
|
|
|
1183
1210
|
"This app or its model source is turned off.": "client_source_disabled_message",
|
|
1184
1211
|
"The request was rejected locally before an upstream call.": "local_validation_message",
|
|
1185
1212
|
"The source's token-count endpoint returned HTTP 404. Message generation is separate.": "count_endpoint_missing_message",
|
|
1213
|
+
"Output limit reached.": "output_limit_reached",
|
|
1214
|
+
"Connection to the model source failed.": "source_connection_failed",
|
|
1186
1215
|
"HTTP request failed; original response was preserved.": "http_request_failed_original_response_was_preserved",
|
|
1187
1216
|
"phase": "phase",
|
|
1188
1217
|
"http_status": "http_status",
|
package/src/dashboard/status.js
CHANGED
|
@@ -106,10 +106,10 @@
|
|
|
106
106
|
const failures = [...grouped.values()].slice(-10);
|
|
107
107
|
const recorded = new Set(failures.map((failure) => failure.request_id).filter(Boolean));
|
|
108
108
|
for (const request of requests) {
|
|
109
|
-
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;
|
|
110
110
|
failures.push({ at: request.at, model: request.model, request_id: request.request_id,
|
|
111
111
|
event_type: `request.${request.outcome}`, code: request.origin, timeline: request,
|
|
112
|
-
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 });
|
|
113
113
|
}
|
|
114
114
|
failures.sort((a, b) => (Date.parse(a.at) || 0) - (Date.parse(b.at) || 0));
|
|
115
115
|
failures.splice(0, Math.max(0, failures.length - 10));
|
|
@@ -123,6 +123,7 @@
|
|
|
123
123
|
return;
|
|
124
124
|
}
|
|
125
125
|
for (const failure of failures) {
|
|
126
|
+
const notModelRequest = ["not_found", "image_mcp", "models", "claude_models"].includes(failure.route);
|
|
126
127
|
const item = document.createElement("li");
|
|
127
128
|
const details = document.createElement("details");
|
|
128
129
|
details.dataset.key = `${failure.at}/${failure.request_id || failure.response_id}/${failure.code}`;
|
|
@@ -131,7 +132,7 @@
|
|
|
131
132
|
const summary = {
|
|
132
133
|
detail: phrase("time_model_code", {
|
|
133
134
|
time: failure.at ? time(failure.at, { date: true }) : phrase("unknown_time"),
|
|
134
|
-
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"),
|
|
135
136
|
code: failure.code ? String(failure.code).slice(0, 80) : phrase("unknown_error"),
|
|
136
137
|
}),
|
|
137
138
|
retry: phrase(failure.upstream_attempts === 0 ? "no_upstream_call" : failure.retried ? "retry_attempted" : "no_retry"),
|
|
@@ -151,7 +152,7 @@
|
|
|
151
152
|
const timings = timeline?.timings_ms || {};
|
|
152
153
|
const timingText = ["admission", "body", "history", "images", "serialization", "upstream_start", "upstream_headers", "first_output", "last_activity", "terminal", "finished"]
|
|
153
154
|
.filter((key) => finite(timings[key])).map((key) => `${key}=${Number(timings[key]).toFixed(1)}`).join(" / ");
|
|
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,
|
|
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,
|
|
155
156
|
message: failure.message, response_id: failure.response_id, upstream_request_id: failure.upstream_request_id,
|
|
156
157
|
retry: failure.retried ? (timeline ? "attempted" : "attempted (outcome not recorded here)") : "not attempted",
|
|
157
158
|
retry_policy: failure.retry_policy, retry_skipped: failure.retry_skipped,
|
|
@@ -162,7 +163,9 @@
|
|
|
162
163
|
error_type: failure.error_type, parameter: failure.parameter, error_body: failure.error_body,
|
|
163
164
|
diagnostic_message: failure.diagnostic_message, method: failure.method, target: failure.target,
|
|
164
165
|
request_options: failure.request_options ? JSON.stringify(failure.request_options) : undefined,
|
|
165
|
-
|
|
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,
|
|
166
169
|
attempt_timings: failure.attempt_timings || timeline?.attempts ? JSON.stringify(failure.attempt_timings || timeline.attempts) : undefined,
|
|
167
170
|
timings_ms: timingText };
|
|
168
171
|
const diagnostic = document.createElement("dl");
|
|
@@ -198,6 +201,7 @@
|
|
|
198
201
|
|
|
199
202
|
function render(data) {
|
|
200
203
|
for (const source of data.providers?.connections?.providers || []) sourceNames.set(source.id, source.name);
|
|
204
|
+
globalThis.ccdxConnections?.updateMemory?.(data.providers?.connections);
|
|
201
205
|
globalThis.ccdxDashboardActivity?.update(data.model_activity);
|
|
202
206
|
globalThis.ccdxDashboardFlow?.update(data);
|
|
203
207
|
text("version", `v${data.version || "?"}`);
|
|
@@ -326,7 +330,9 @@
|
|
|
326
330
|
String(sourceLabel(request.provider) || "—").slice(0, 80),
|
|
327
331
|
String(request.model || "unknown").slice(0, 80), outcome, number(context.input_tokens), ""], { labels: [3] });
|
|
328
332
|
const wireFailure = Number.isInteger(request.http_status) && request.http_status >= 400;
|
|
329
|
-
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(),
|
|
330
336
|
wireFailure ? "warning" : globalThis.ccdxIcons.kind(outcome.toLowerCase()), wireFailure ? { status: request.http_status } : {});
|
|
331
337
|
else if (wireFailure) localize(row.children[3], "request_http_failure", { status: request.http_status });
|
|
332
338
|
const details = document.createElement("details"), summary = document.createElement("summary"), fields = document.createElement("dl");
|
|
@@ -337,7 +343,8 @@
|
|
|
337
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],
|
|
338
344
|
["time", Number.isFinite(at) ? time(at, { date: true }) : "—"],
|
|
339
345
|
["wire_mib", finite(context.payload_bytes) ? `${(Number(context.payload_bytes) / 1048576).toFixed(2)} MiB` : "—"],
|
|
340
|
-
["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 || "—"]]) {
|
|
341
348
|
const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);detail.textContent = value;fields.append(term, detail);
|
|
342
349
|
}
|
|
343
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; }
|
|
@@ -528,3 +528,26 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
528
528
|
@media(max-width:640px) { .nightly-rules { grid-template-columns:1fr; } }
|
|
529
529
|
|
|
530
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),
|
|
@@ -2,60 +2,65 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
|
|
3
3
|
import { readBoundedResponseText } from "../http-transport.mjs";
|
|
4
4
|
|
|
5
|
-
//
|
|
6
|
-
//
|
|
5
|
+
// One API/key configuration owns these bounded observations and operations.
|
|
6
|
+
// Unknown capabilities share their first real count, not another inference.
|
|
7
7
|
export function createApiTokenCounter({ request, now = Date.now }) {
|
|
8
|
-
const flights = new Map(),
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
{ status: 404, headers: { "Content-Type": "application/json" } });
|
|
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); };
|
|
13
12
|
return {
|
|
14
13
|
async count(body, options = {}) {
|
|
15
14
|
if (options.signal?.aborted) throw options.signal.reason;
|
|
16
15
|
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
|
-
|
|
19
|
-
if (
|
|
20
|
-
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
flights.
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
+
};
|
|
37
51
|
try {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}
|
|
47
|
-
|
|
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; }
|
|
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
|
+
}
|
|
58
62
|
}
|
|
63
|
+
return run(!capabilities.has(scope));
|
|
59
64
|
},
|
|
60
65
|
};
|
|
61
66
|
}
|
package/src/providers/api.mjs
CHANGED
|
@@ -15,16 +15,17 @@ import { apiModelMetadata } from "./api-model-metadata.mjs";
|
|
|
15
15
|
import { markRequestObservation, markUpstreamStarted } from "../stream-performance.mjs";
|
|
16
16
|
import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
|
|
17
17
|
import { createApiTokenCounter } from "./api-token-count.mjs";
|
|
18
|
+
import { apiModelDisplay } from "../api-model-display.mjs";
|
|
18
19
|
|
|
19
20
|
const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
|
|
20
21
|
export function apiCatalog(config, env = process.env) {
|
|
21
22
|
const revision = deploymentRevision(config, env);
|
|
22
23
|
return config.models.map(model => { const protocol_capabilities = Object.fromEntries(model.protocols.map(protocol => [protocol, resolveModelCapabilities(model, { revision, protocol })]));
|
|
23
|
-
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,
|
|
24
25
|
supported_endpoints: model.protocols.map(api => paths[api]), model_picker_enabled: true, policy: { state: "enabled" },
|
|
25
26
|
capability, protocol_capabilities }); });
|
|
26
27
|
}
|
|
27
|
-
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 = () => ({}) } = {}) {
|
|
28
29
|
const catalog = apiCatalog(config, env);
|
|
29
30
|
const fingerprint = config.key_env ? createHash("sha256").update(env[config.key_env] || "").digest("hex") : "";
|
|
30
31
|
const generation = parseInt(createHash("sha256").update(JSON.stringify(config) + fingerprint).digest("hex").slice(0, 8), 16);
|
|
@@ -68,11 +69,15 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
68
69
|
const constrained = constrainModelRequest(body, capability, api);
|
|
69
70
|
if (constrained.body !== body) { body = constrained.body;options = { ...options, bodyText: undefined }; }
|
|
70
71
|
markRequestObservation({ capability_revision: capability?.revision, capability_constraints: constrained.applied.join(",") || "none" });
|
|
72
|
+
markRequestObservation({ context_window_tokens: capability?.values.context_window });
|
|
71
73
|
}
|
|
72
74
|
const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
|
|
73
75
|
if (serialized !== undefined) headers["Content-Length"] = String(Buffer.byteLength(serialized));
|
|
74
76
|
options.onUpstreamStart?.();
|
|
75
|
-
if (body && options.observeUpstream !== false)
|
|
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
|
+
}
|
|
76
81
|
try {
|
|
77
82
|
const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
|
|
78
83
|
if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
|
|
@@ -119,7 +124,8 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
119
124
|
.map(model => ({ ...model, capability: model.protocol_capabilities[family === "claude" ? "messages" : "responses"] })),
|
|
120
125
|
catalog: () => catalog,
|
|
121
126
|
publicCatalog(allowed = []) { return { source: "configured", checkedAt: config.checked_at || null, upstreamHost: new URL(config.base_url).hostname,
|
|
122
|
-
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)),
|
|
123
129
|
clients: model => allowed.filter(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)) }).map(model => ({ ...model,
|
|
124
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 || [])] })) }; },
|
|
125
131
|
async discover({ signal } = {}) {
|
|
@@ -136,7 +142,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
136
142
|
if (!Array.isArray(value.data) || models.length + value.data.length > 500) throw accessError("ccdx_api_catalog_invalid", 502);
|
|
137
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); }
|
|
138
144
|
// A catalog listing is not evidence that every model supports every API.
|
|
139
|
-
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)
|
|
140
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]) : [] })));
|
|
141
147
|
if (value.has_more !== true) return models;
|
|
142
148
|
// Follow only the native cursor on the configured origin, never an
|