codex-copilot-dx 1.2.12 → 1.2.13
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 +14 -14
- package/bin/cli.mjs +12 -8
- package/docs/ARCHITECTURE.md +48 -5
- package/docs/REFERENCE.md +87 -1
- package/package.json +2 -2
- package/src/access-settings.mjs +98 -0
- package/src/adapter.mjs +19 -7
- package/src/api-secrets.mjs +69 -0
- package/src/auto-review-model.mjs +4 -3
- package/src/claude-client-config.mjs +16 -11
- package/src/claude-gateway.mjs +11 -8
- package/src/cli-m365.mjs +48 -8
- package/src/cli-models.mjs +2 -1
- package/src/cli-options.mjs +1 -1
- package/src/cli-status.mjs +1 -1
- package/src/client-gateway-keys.mjs +29 -0
- package/src/codex-api-config.mjs +51 -0
- package/src/connection-runtime.mjs +289 -0
- package/src/conversation-source-guard.mjs +42 -0
- package/src/dashboard/connections.js +163 -0
- package/src/dashboard/console.js +6 -4
- package/src/dashboard/flow.js +4 -4
- package/src/dashboard/index.html +43 -0
- package/src/dashboard/language.js +82 -2
- package/src/dashboard/status.js +1 -1
- package/src/dashboard/ui.css +21 -0
- package/src/dashboard/ui.js +4 -2
- package/src/dashboard-api.mjs +19 -4
- package/src/dashboard.mjs +1 -0
- package/src/optional-routes.mjs +2 -2
- package/src/private-helper-environment.mjs +7 -0
- package/src/provider-management.mjs +1 -1
- package/src/provider-runtime.mjs +37 -5
- package/src/providers/api-network.mjs +51 -0
- package/src/providers/api.mjs +129 -0
- package/src/proxy-tunnel.mjs +6 -4
- package/src/responses-handler.mjs +6 -4
- package/src/startup-ui.mjs +9 -0
- package/src/stream-performance.mjs +7 -6
- package/src/terminal-console.mjs +1 -1
- package/src/usage-store.mjs +1 -1
- package/src/windows-http-network.mjs +11 -6
- package/src/windows-prediction-network.cs +6 -4
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { createRoutePlan } from "../route-plan.mjs";
|
|
3
|
+
import { accessError } from "../access-settings.mjs";
|
|
4
|
+
import { publicModelCatalog } from "../provider-metadata.mjs";
|
|
5
|
+
import { resolveClaudeModel } from "../claude-models.mjs";
|
|
6
|
+
import { prepareResponsesPayload } from "../image-optimization.mjs";
|
|
7
|
+
import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
|
|
8
|
+
import { MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "../http-transport.mjs";
|
|
9
|
+
import { markUpstreamHeaders } from "../stream-performance.mjs";
|
|
10
|
+
import { createApiNetwork } from "./api-network.mjs";
|
|
11
|
+
import { checkedApiKey } from "../api-secrets.mjs";
|
|
12
|
+
|
|
13
|
+
const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
|
|
14
|
+
export function apiCatalog(config) {
|
|
15
|
+
return config.models.map(model => ({ id: model.id, name: model.id, publisher: "Unknown",
|
|
16
|
+
supported_endpoints: model.protocols.map(api => paths[api]), model_picker_enabled: true, policy: { state: "enabled" },
|
|
17
|
+
capabilities: { limits: { max_context_window_tokens: model.context_window }, supports: { reasoning_effort: model.reasoning_efforts || [] } } }));
|
|
18
|
+
}
|
|
19
|
+
export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork } = {}) {
|
|
20
|
+
const catalog = apiCatalog(config), declarations = new Map(config.models.map(model => [model.id, model]));
|
|
21
|
+
const fingerprint = config.key_env ? createHash("sha256").update(env[config.key_env] || "").digest("hex") : "";
|
|
22
|
+
const generation = parseInt(createHash("sha256").update(JSON.stringify(config) + fingerprint).digest("hex").slice(0, 8), 16);
|
|
23
|
+
const profiles = Object.fromEntries(["messages", "responses", "chat"].map(protocol => [protocol, `api:${config.id}:${createHash("sha256").update(JSON.stringify({
|
|
24
|
+
endpoint: config.endpoints[protocol] ? new URL(config.endpoints[protocol]).href : null, key: config.secret_ref || fingerprint, auth: protocol === "messages" ? config.auth_header : "bearer",
|
|
25
|
+
})).digest("hex").slice(0, 24)}`]));
|
|
26
|
+
const profile = profiles.responses;
|
|
27
|
+
const modelsUrl = config.base_url.replace(/\/+$/, "") + "/models", targets = [...Object.values(config.endpoints), modelsUrl];
|
|
28
|
+
if (config.endpoints.messages) targets.push(config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens");
|
|
29
|
+
if (config.endpoints.responses) targets.push(config.endpoints.responses.replace(/\/+$/, "") + "/compact");
|
|
30
|
+
let network, flight, closed = false;
|
|
31
|
+
const registry = { models: { data: catalog.filter(model => model.supported_endpoints.includes(paths.responses)) }, source: "configured", generation };
|
|
32
|
+
const getNetwork = async signal => {
|
|
33
|
+
if (closed) throw accessError("ccdx_api_closed", 503);
|
|
34
|
+
if (network && (network.healthy?.() ?? true)) return network;
|
|
35
|
+
network?.close();network = null;
|
|
36
|
+
flight ||= networkFactory({ targets, env, platform, signal }).then(value => { if (closed) { value.close();throw accessError("ccdx_api_closed", 503); }network = value;return value; }).finally(() => { flight = null; });
|
|
37
|
+
return flight;
|
|
38
|
+
};
|
|
39
|
+
const selected = (id, api) => {
|
|
40
|
+
const model = api === "messages" ? resolveClaudeModel(catalog, id) : catalog.find(model => model.id === id);
|
|
41
|
+
if (!model?.supported_endpoints.includes(paths[api])) throw accessError("ccdx_api_model_unavailable");return model;
|
|
42
|
+
};
|
|
43
|
+
async function request(url, body, options = {}, api = "responses") {
|
|
44
|
+
if (config.key_env && !env[config.key_env]) throw accessError("ccdx_api_environment_key_missing", 503);
|
|
45
|
+
const key = config.key_env ? checkedApiKey(env[config.key_env]) : await secrets.get(config.secret_ref), transport = await getNetwork(options.signal);
|
|
46
|
+
const headers = { "Content-Type": "application/json", Accept: body?.stream ? "text/event-stream" : "application/json" };
|
|
47
|
+
headers[api === "messages" && config.auth_header === "x-api-key" ? "x-api-key" : "Authorization"] = api === "messages" && config.auth_header === "x-api-key" ? key : `Bearer ${key}`;
|
|
48
|
+
if (api === "messages") {
|
|
49
|
+
headers["anthropic-version"] = "2023-06-01";
|
|
50
|
+
for (const name of ["anthropic-version", "anthropic-beta"]) { const value = options.headers?.[name];if (typeof value === "string" && value.length < 8192 && !/[\r\n]/.test(value)) headers[name] = value; }
|
|
51
|
+
}
|
|
52
|
+
const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
|
|
53
|
+
if (serialized !== undefined) headers["Content-Length"] = String(Buffer.byteLength(serialized));
|
|
54
|
+
options.onUpstreamStart?.();
|
|
55
|
+
try {
|
|
56
|
+
const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
|
|
57
|
+
if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
|
|
58
|
+
if (!result.ok) {
|
|
59
|
+
await result.body?.cancel();const code = `ccdx_api_http_${result.status}`;
|
|
60
|
+
const safeHeaders = { "Content-Type": "application/json" }, retry = result.headers.get("retry-after");
|
|
61
|
+
if (/^\d{1,8}$/.test(retry || "")) safeHeaders["Retry-After"] = retry;
|
|
62
|
+
else if (retry && Number.isFinite(Date.parse(retry))) safeHeaders["Retry-After"] = new Date(retry).toUTCString();
|
|
63
|
+
return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message: code } }), { status: result.status, headers: safeHeaders });
|
|
64
|
+
}
|
|
65
|
+
return result;
|
|
66
|
+
} catch (error) { if (options.signal?.aborted) throw error;throw accessError(error.code === "ccdx_api_redirect_refused" ? error.code : "ccdx_api_network_unavailable", 502); }
|
|
67
|
+
}
|
|
68
|
+
const client = {
|
|
69
|
+
listModels: async () => ({ status: 200, body: JSON.stringify(registry.models) }),
|
|
70
|
+
getCachedModelEndpoints: id => catalog.find(model => model.id === id)?.supported_endpoints || null,
|
|
71
|
+
async responses(body, options = {}) {
|
|
72
|
+
selected(body.model, "responses");
|
|
73
|
+
const prepared = await prepareResponsesPayload(body, { ...options.payloadOptions, assertActive: options.assertActive,
|
|
74
|
+
currentInputStart: options.currentInputStart || 0, signal: options.signal, profiles: options.payloadPrepared ? [] : options.payloadOptions?.profiles,
|
|
75
|
+
skipInitialOptimization: options.payloadPrepared || options.payloadOptions?.skipInitialOptimization });
|
|
76
|
+
const final = enforceResponsesPayloadByteBudget(body, prepared, { assertActive: options.assertActive });
|
|
77
|
+
return request(config.endpoints.responses, body, { ...options, bodyText: final.bodyText });
|
|
78
|
+
},
|
|
79
|
+
responsesCompact(body, options = {}) { selected(body.model, "responses");return request(config.endpoints.responses.replace(/\/+$/, "") + "/compact", body, options); },
|
|
80
|
+
chatCompletions(body, options = {}) { selected(body.model, "chat");return request(config.endpoints.chat, body, options, "chat"); },
|
|
81
|
+
messages(body, options = {}) {
|
|
82
|
+
const model = selected(body.model, "messages");
|
|
83
|
+
return request(options.countTokens ? config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens" : config.endpoints.messages, model.id === body.model ? body : { ...body, model: model.id }, options, "messages");
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
return {
|
|
87
|
+
id: config.id, client, registry, configuredModels: true, defaultReviewEffort: null, profileId: (protocol = "responses") => profiles[protocol] || profile, models: family => catalog.filter(model => model.supported_endpoints.includes(family === "claude" ? paths.messages : paths.responses)),
|
|
88
|
+
codexCatalog(models) {
|
|
89
|
+
return { ...models, models: config.models.filter(model => model.protocols.includes("responses")).map((model, priority) => ({
|
|
90
|
+
slug: model.id, display_name: model.id, description: config.name, visibility: "list", supported_in_api: true, priority,
|
|
91
|
+
default_reasoning_level: model.reasoning_efforts?.[0] || null, supported_reasoning_levels: (model.reasoning_efforts || []).map(effort => ({ effort, description: effort })),
|
|
92
|
+
shell_type: "unified_exec", availability_nux: null, upgrade: null, additional_speed_tiers: [], service_tiers: [],
|
|
93
|
+
// Neutral metadata for a native Responses API. Never borrow another model's instructions or capabilities.
|
|
94
|
+
base_instructions: "", support_verbosity: false, default_verbosity: null, apply_patch_tool_type: null,
|
|
95
|
+
supports_reasoning_summary_parameter: false, default_reasoning_summary: "none", truncation_policy: { mode: "bytes", limit: 10000 },
|
|
96
|
+
context_window: model.context_window || null, max_context_window: model.context_window || null, experimental_supported_tools: [], input_modalities: ["text"],
|
|
97
|
+
})) };
|
|
98
|
+
},
|
|
99
|
+
catalog: () => catalog,
|
|
100
|
+
publicCatalog(allowed = []) { return { source: "configured", checkedAt: config.checked_at || null, upstreamHost: new URL(config.base_url).hostname,
|
|
101
|
+
advertised: catalog.length, models: publicModelCatalog(catalog, { selectable: model => allowed.some(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)),
|
|
102
|
+
clients: model => allowed.filter(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)) }).map(model => ({ ...model,
|
|
103
|
+
auto_review_efforts: [...(declarations.get(model.id)?.reasoning_efforts || [])] })) }; },
|
|
104
|
+
async discover({ signal } = {}) {
|
|
105
|
+
const response = await request(modelsUrl, undefined, { signal }, config.endpoints.responses ? "responses" : "messages");
|
|
106
|
+
if (!response.ok) { await response.body?.cancel();throw accessError(`ccdx_api_catalog_http_${response.status}`, response.status === 401 || response.status === 403 ? response.status : 502); }
|
|
107
|
+
const text = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES, label: "API model catalog", signal });
|
|
108
|
+
let value;try { value = JSON.parse(text); } catch { throw accessError("ccdx_api_catalog_invalid", 502); }
|
|
109
|
+
if (!Array.isArray(value.data) || value.data.length > 500) throw accessError("ccdx_api_catalog_invalid", 502);
|
|
110
|
+
const ids = new Set();
|
|
111
|
+
for (const model of value.data) { if (!model || typeof model.id !== "string" || !/^[\w][\w./:@+-]{0,159}$/.test(model.id) || ids.has(model.id)) throw accessError("ccdx_api_catalog_invalid", 502);ids.add(model.id); }
|
|
112
|
+
// A catalog listing is not evidence that every model supports every API.
|
|
113
|
+
return value.data.map(model => ({ id: model.id, protocols: Array.isArray(model.supported_endpoints)
|
|
114
|
+
? 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]) : [] }));
|
|
115
|
+
},
|
|
116
|
+
selectModel(_body, { upstreamModel }) { selected(upstreamModel, "responses");return { upstreamModel, forceResponses: true }; },
|
|
117
|
+
route(_body, { upstreamModel, surface }) { return createRoutePlan({ disposition: "relay", origin: config.id, profile, protocol: "openai-responses", model: upstreamModel, surface }); },
|
|
118
|
+
applyRequestPolicies() {},
|
|
119
|
+
compatibility: { hasRetry: () => false, selectRetry: async () => null,
|
|
120
|
+
async openResponse(context, upstream, options) {
|
|
121
|
+
const resp = await upstream(context.body, { assertActive: options.assertPrepareActive, signal: options.signal, currentInputStart: context.currentInputStart, onUpstreamStart: options.onUpstreamStart });
|
|
122
|
+
markUpstreamHeaders(resp.status);
|
|
123
|
+
// Upstream errors may echo its key; never forward its error body.
|
|
124
|
+
if (!resp.ok) { await resp.body?.cancel();const code = `ccdx_api_http_${resp.status}`;return { resp: new Response(JSON.stringify({ error: { code, message: code } }), { status: resp.status, headers: { "Content-Type": "application/json" } }), reqContext: context, errorText: code, usedRetryPolicies: new Set() }; }
|
|
125
|
+
return { resp, reqContext: context, errorText: undefined, usedRetryPolicies: new Set() };
|
|
126
|
+
} },
|
|
127
|
+
close() { closed = true;network?.close(); },
|
|
128
|
+
};
|
|
129
|
+
}
|
package/src/proxy-tunnel.mjs
CHANGED
|
@@ -26,6 +26,7 @@ function readSocket(socket, ready, maxBytes = 16 * 1024) {
|
|
|
26
26
|
|
|
27
27
|
async function connectProxy(target, route, timeoutMs, pending) {
|
|
28
28
|
const proxy = route.url;
|
|
29
|
+
const targetPort = Number(target.port || 443);
|
|
29
30
|
const proxyHost = proxy.hostname.replace(/^\[|\]$/g, "");
|
|
30
31
|
const socket = proxy.protocol === "https:"
|
|
31
32
|
? tls.connect({ host: proxyHost, port: Number(proxy.port || 443), servername: net.isIP(proxyHost) ? undefined : proxyHost, rejectUnauthorized: true })
|
|
@@ -52,21 +53,21 @@ async function connectProxy(target, route, timeoutMs, pending) {
|
|
|
52
53
|
socket.write(Buffer.concat([Buffer.from([1, user.length]), user, Buffer.from([password.length]), password]));
|
|
53
54
|
const result = await auth; if (result[0] !== 1 || result[1] !== 0) throw new Error("SOCKS5 proxy authentication failed");
|
|
54
55
|
}
|
|
55
|
-
const host = Buffer.from(target.hostname);
|
|
56
|
+
const host = Buffer.from(target.hostname.replace(/^\[|\]$/g, ""));
|
|
56
57
|
if (host.length > 255) throw new Error("Proxy target hostname is too long");
|
|
57
58
|
const response = readSocket(socket, b => {
|
|
58
59
|
if (b.length < 5) return null;
|
|
59
60
|
const size = b[3] === 1 ? 10 : b[3] === 4 ? 22 : b[3] === 3 ? 7 + b[4] : 5;
|
|
60
61
|
return b.length >= size ? size : null;
|
|
61
62
|
});
|
|
62
|
-
socket.write(Buffer.concat([Buffer.from([5, 1, 0, 3, host.length]), host, Buffer.from([
|
|
63
|
+
socket.write(Buffer.concat([Buffer.from([5, 1, 0, 3, host.length]), host, Buffer.from([targetPort >> 8, targetPort & 255])]));
|
|
63
64
|
const result = await response;
|
|
64
65
|
if (result[0] !== 5 || result[1] !== 0 || ![1, 3, 4].includes(result[3])) throw new Error("SOCKS5 proxy rejected the connection");
|
|
65
66
|
} else {
|
|
66
67
|
const response = readSocket(socket, b => { const end = b.indexOf("\r\n\r\n"); return end < 0 ? null : end + 4; });
|
|
67
68
|
const credentials = proxy.username || proxy.password
|
|
68
69
|
? `Proxy-Authorization: Basic ${Buffer.from(`${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`).toString("base64")}\r\n` : "";
|
|
69
|
-
socket.write(`CONNECT ${target.hostname}
|
|
70
|
+
socket.write(`CONNECT ${target.hostname}:${targetPort} HTTP/1.1\r\nHost: ${target.hostname}:${targetPort}\r\n${credentials}\r\n`);
|
|
70
71
|
const headers = (await response).toString("latin1");
|
|
71
72
|
const status = /^HTTP\/1\.[01] (\d{3})/.exec(headers)?.[1];
|
|
72
73
|
if (status !== "200") throw new Error(`HTTP proxy rejected CONNECT (${status || "invalid response"})`);
|
|
@@ -83,7 +84,8 @@ export function createProxyAgent(plan, { timeoutMs = 30_000 } = {}) {
|
|
|
83
84
|
const direct = agent.createConnection.bind(agent);
|
|
84
85
|
agent.createConnection = (options, callback) => {
|
|
85
86
|
if (closed) { queueMicrotask(() => callback(new Error("Proxy agent is closed"))); return undefined; }
|
|
86
|
-
const
|
|
87
|
+
const host = options.hostname || options.host;
|
|
88
|
+
const target = new URL(`https://${net.isIP(host) === 6 ? `[${host}]` : host}:${options.port || 443}`), route = networkProxyFor(target, plan);
|
|
87
89
|
if (!route) return direct(options, callback);
|
|
88
90
|
void connectProxy(target, route, timeoutMs, pending).then(socket => {
|
|
89
91
|
if (closed) { socket.destroy(); callback(new Error("Proxy agent is closed")); return; }
|
|
@@ -203,6 +203,7 @@ export function createResponsesHandler(options) {
|
|
|
203
203
|
releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
|
|
204
204
|
abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
|
|
205
205
|
parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
|
|
206
|
+
options.validateConversation?.(parsed, req.headers, provider);
|
|
206
207
|
activeDeadline = now() + upstreamTimeoutMs;
|
|
207
208
|
activeTimeoutReason = "responses_prepare_timeout";
|
|
208
209
|
abort.setTimeout(upstreamTimeoutMs, "responses_prepare_timeout");
|
|
@@ -237,12 +238,12 @@ export function createResponsesHandler(options) {
|
|
|
237
238
|
const { upstreamModel, forceResponses } = provider.selectModel(prepared.body, resolvedModel, modelRegistry?.models);
|
|
238
239
|
if (requestedModel === CODEX_AUTO_REVIEW_MODEL) {
|
|
239
240
|
delete prepared.body.service_tier;
|
|
240
|
-
if (resolvedModel.reasoningEffort || prepared.body.reasoning?.effort === undefined) {
|
|
241
|
+
if (resolvedModel.reasoningEffort || provider.defaultReviewEffort !== null && prepared.body.reasoning?.effort === undefined) {
|
|
241
242
|
prepared.body.reasoning = { ...prepared.body.reasoning, effort: resolvedModel.reasoningEffort || "low" };
|
|
242
243
|
}
|
|
243
244
|
}
|
|
244
245
|
if (upstreamModel !== requestedModel) prepared.body.model = upstreamModel;
|
|
245
|
-
markResponseModel(upstreamModel, { requestedModel });
|
|
246
|
+
markResponseModel(upstreamModel, { requestedModel, configuredModel: provider.configuredModels === true });
|
|
246
247
|
markRequestObservation({ context_window_tokens: modelContextWindowTokens(modelRegistry?.models, upstreamModel) });
|
|
247
248
|
const upstreamLog = upstreamModel === requestedModel ? "" : ` upstream_model=${upstreamModel}`;
|
|
248
249
|
console.log(status("info", `responses model=${requestedModel}${upstreamLog} stream=${streaming}`));
|
|
@@ -474,6 +475,7 @@ export function createResponsesCompactHandler(options) {
|
|
|
474
475
|
releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
|
|
475
476
|
abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
|
|
476
477
|
const parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
|
|
478
|
+
options.validateConversation?.(parsed, req.headers, provider);
|
|
477
479
|
activeDeadline = now() + upstreamTimeoutMs;
|
|
478
480
|
activeTimeoutReason = "responses_prepare_timeout";
|
|
479
481
|
abort.setTimeout(upstreamTimeoutMs, "responses_prepare_timeout");
|
|
@@ -506,7 +508,7 @@ export function createResponsesCompactHandler(options) {
|
|
|
506
508
|
const { upstreamModel, forceResponses } = provider.selectModel(prepared.body, resolvedModel, modelRegistry?.models);
|
|
507
509
|
if (requestedModel === CODEX_AUTO_REVIEW_MODEL) {
|
|
508
510
|
delete prepared.body.service_tier;
|
|
509
|
-
if (resolvedModel.reasoningEffort || prepared.body.reasoning?.effort === undefined) {
|
|
511
|
+
if (resolvedModel.reasoningEffort || provider.defaultReviewEffort !== null && prepared.body.reasoning?.effort === undefined) {
|
|
510
512
|
prepared.body.reasoning = { ...prepared.body.reasoning, effort: resolvedModel.reasoningEffort || "low" };
|
|
511
513
|
}
|
|
512
514
|
}
|
|
@@ -514,7 +516,7 @@ export function createResponsesCompactHandler(options) {
|
|
|
514
516
|
markRequestObservation({ context_window_tokens: modelContextWindowTokens(modelRegistry?.models, upstreamModel) });
|
|
515
517
|
const upstreamLog = upstreamModel === requestedModel ? "" : ` upstream_model=${upstreamModel}`;
|
|
516
518
|
console.log(status("info", `responses compact model=${requestedModel}${upstreamLog} stream=false`));
|
|
517
|
-
markResponseModel(upstreamModel, { requestedModel });
|
|
519
|
+
markResponseModel(upstreamModel, { requestedModel, configuredModel: provider.configuredModels === true });
|
|
518
520
|
const selected = applySelectedRoute(prepared, provider.route(prepared.body, {
|
|
519
521
|
requestedModel, upstreamModel, forceResponses, surface: "responses-compact" }), { req, env: openAIModelEnv,
|
|
520
522
|
signal: abort.signal, assertActive: assertPrepareActive, reserveHistory: releaseRequest.reserveResponseHistory });
|
package/src/startup-ui.mjs
CHANGED
|
@@ -60,6 +60,15 @@ export function predictionStartupCheck(prediction) {
|
|
|
60
60
|
// Catalog discovery, client configuration and inference access are distinct.
|
|
61
61
|
export function providerStartupSummary(data = {}) {
|
|
62
62
|
if (!data.providers) return { catalogs: "Status unavailable; see WebUI", claude: "Configuration not checked", warning: false };
|
|
63
|
+
const connections = data.providers.connections;
|
|
64
|
+
if (connections?.managed) {
|
|
65
|
+
const enabled = connections.providers.filter(provider => provider.enabled);
|
|
66
|
+
const states = { configured: "configured", not_configured: "not configured", not_installed: "not installed", preserved: "custom settings kept", configuration_unavailable: "config unavailable", partially_preserved: "partly configured", unavailable: "source unavailable" };
|
|
67
|
+
const sourceLines = enabled.map(provider => `${terminalCell(provider.name)} / ${provider.builtin ? provider.id === "m365" ? terminalCell(connections.m365_state) : "sign-in checked separately" : `${provider.model_count} configured models`}`);
|
|
68
|
+
const claudeLines = connections.clients.filter(client => client.id !== "codex").map(client => `${client.name}: ${!client.enabled ? "off" : client.source ? states[client.setup] || "not checked" : "paused"}`);
|
|
69
|
+
return { catalogs: `${enabled.length} enabled source${enabled.length === 1 ? "" : "s"}`, claude: claudeLines.join(" / "), sourceLines, claudeLines,
|
|
70
|
+
compactSources: sourceLines.length ? sourceLines : ["No source enabled"], compactClaude: claudeLines, warning: connections.clients.some(client => client.setup === "configuration_unavailable") };
|
|
71
|
+
}
|
|
63
72
|
const providers = data.providers, ms = providers?.m365;
|
|
64
73
|
const github = data.profiles?.codex?.models || (data.models?.provider !== "m365" ? data.models : null);
|
|
65
74
|
const found = catalog => ["cache", "live"].includes(catalog?.source) && Number.isSafeInteger(catalog?.models ?? catalog?.total) && (catalog.models ?? catalog.total) > 0;
|
|
@@ -14,7 +14,7 @@ const TERMINAL_ORIGINS = new Set([
|
|
|
14
14
|
const MAX_MODEL_OUTCOME_LABELS = 32;
|
|
15
15
|
const MAX_RECENT_REQUESTS = 20;
|
|
16
16
|
const MAX_ACTIVE_REQUESTS = 64;
|
|
17
|
-
const MAX_PROVIDER_LABELS =
|
|
17
|
+
const MAX_PROVIDER_LABELS = 18;
|
|
18
18
|
const PREPARATION_EDGES_MS = Object.freeze([1, 2, 5, 10, 20, 50, 100, 250, 500, 1_000, 5_000, 30_000, 120_000]);
|
|
19
19
|
const TTFT_EDGES_MS = Object.freeze([
|
|
20
20
|
100, 200, 300, 500, 700, 1_000, 1_400, 2_000, 2_800, 4_000,
|
|
@@ -147,8 +147,9 @@ function emptyOutcomes() {
|
|
|
147
147
|
return Object.fromEntries(TERMINAL_OUTCOMES.map((outcome) => [outcome, 0]));
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
-
function modelLabel(value) {
|
|
150
|
+
function modelLabel(value, configured = false) {
|
|
151
151
|
const model = String(value || "").trim();
|
|
152
|
+
if (configured && /^[\w][\w./:@+-]{0,159}$/.test(model)) return model;
|
|
152
153
|
return model === "codex-auto-review" || /^(?:gpt|claude)-[A-Za-z0-9._-]{1,72}$/.test(model)
|
|
153
154
|
? model : "other";
|
|
154
155
|
}
|
|
@@ -317,8 +318,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
317
318
|
const tokens = Number(value);
|
|
318
319
|
if (Number.isFinite(tokens) && tokens >= 0) outputTokens = tokens;
|
|
319
320
|
},
|
|
320
|
-
setModel(value) {
|
|
321
|
-
model = modelLabel(value);
|
|
321
|
+
setModel(value, { configured = false } = {}) {
|
|
322
|
+
model = modelLabel(value, configured);
|
|
322
323
|
},
|
|
323
324
|
setProvider: assignProvider,
|
|
324
325
|
attemptCount() { return attempts; },
|
|
@@ -481,13 +482,13 @@ export function markStreamFailure() {
|
|
|
481
482
|
tracker()?.fail();
|
|
482
483
|
}
|
|
483
484
|
|
|
484
|
-
export function markResponseModel(model, { requestedModel } = {}) {
|
|
485
|
+
export function markResponseModel(model, { requestedModel, configuredModel = false } = {}) {
|
|
485
486
|
const context = currentRequestContext();
|
|
486
487
|
if (context) {
|
|
487
488
|
context.model = model;
|
|
488
489
|
if (requestedModel !== undefined) context.requestedModel = modelLabel(requestedModel);
|
|
489
490
|
}
|
|
490
|
-
tracker()?.setModel?.(model);
|
|
491
|
+
tracker()?.setModel?.(model, { configured: configuredModel });
|
|
491
492
|
}
|
|
492
493
|
|
|
493
494
|
export function markResponseErrorOrigin(origin) {
|
package/src/terminal-console.mjs
CHANGED
|
@@ -76,7 +76,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
|
|
|
76
76
|
}
|
|
77
77
|
if (dirty) {
|
|
78
78
|
const usage = data.runtime_usage || {}, routes = data.requests?.by_route || {};
|
|
79
|
-
const outcomes = [data.stream_performance?.by_route?.responses, data.stream_performance?.by_route?.responses_compact, data.providers?.m365?.claude?.requests?.performance?.by_route?.messages]
|
|
79
|
+
const outcomes = [data.stream_performance?.by_route?.responses, data.stream_performance?.by_route?.responses_compact, (data.providers?.claude || data.providers?.m365?.claude)?.requests?.performance?.by_route?.messages]
|
|
80
80
|
.map(route => route?.terminal_outcomes?.totals || {});
|
|
81
81
|
const sum = key => outcomes.reduce((total, item) => total + (Number(item[key]) || 0), 0);
|
|
82
82
|
const requests = ["responses", "responses_compact", "messages"].reduce((total, key) => total + (routes[key]?.total || 0), 0);
|
package/src/usage-store.mjs
CHANGED
|
@@ -192,7 +192,7 @@ export function recordUsage(record) {
|
|
|
192
192
|
if (!record) return Promise.resolve();
|
|
193
193
|
const usage = record.usage || {};
|
|
194
194
|
const { cached, unknown, invalid } = usageCacheEvidence(usage);
|
|
195
|
-
const provider = usageProvider(record), label = runtimeUsageByProvider.has(provider) || runtimeUsageByProvider.size <
|
|
195
|
+
const provider = usageProvider(record), label = runtimeUsageByProvider.has(provider) || runtimeUsageByProvider.size < 18 ? provider : "other";
|
|
196
196
|
if (!runtimeUsageByProvider.has(label)) runtimeUsageByProvider.set(label, { records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 });
|
|
197
197
|
for (const totals of [runtimeUsage, runtimeUsageByProvider.get(label)]) {
|
|
198
198
|
totals.records++;
|
|
@@ -10,10 +10,13 @@ function failure(code) {
|
|
|
10
10
|
|
|
11
11
|
// Private, credit-based WinHTTP transport. Each consumer owns its worker and a
|
|
12
12
|
// fixed target group; prediction and M365 cannot share credentials or requests.
|
|
13
|
-
export async function startWindowsHttpNetwork({ settings = {}, target = "prediction", validatePac = () => {}, env = process.env, spawnImpl = spawn, timeoutMs = 30_000, onFailure = () => {}, signal } = {}) {
|
|
13
|
+
export async function startWindowsHttpNetwork({ settings = {}, target = "prediction", apiTargets = [], validatePac = () => {}, env = process.env, spawnImpl = spawn, timeoutMs = 30_000, onFailure = () => {}, signal } = {}) {
|
|
14
14
|
signal?.throwIfAborted();
|
|
15
|
-
if (!["prediction", "m365"].includes(target)) throw failure("proxy_target_invalid");
|
|
16
|
-
|
|
15
|
+
if (!["prediction", "m365", "api"].includes(target)) throw failure("proxy_target_invalid");
|
|
16
|
+
if (target === "api" && (!Array.isArray(apiTargets) || !apiTargets.length || apiTargets.length > 8 || apiTargets.some(raw => {
|
|
17
|
+
try { const url = new URL(raw);return url.protocol !== "https:" || url.username || url.password || url.search || url.hash || url.href !== raw; } catch { return true; }
|
|
18
|
+
}))) throw failure("proxy_target_invalid");
|
|
19
|
+
const allowedHosts = target === "api" ? apiTargets.map(raw => new URL(raw).hostname) : target === "m365" ? ["df.loki.delve.office.com"] : ["chatgpt.com", "ab.chatgpt.com"];
|
|
17
20
|
const command = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
18
21
|
const source = fileURLToPath(new URL("./windows-prediction-network.cs", import.meta.url));
|
|
19
22
|
const child = spawnImpl(command, ["-NoProfile", "-NonInteractive", "-Command",
|
|
@@ -54,7 +57,7 @@ export async function startWindowsHttpNetwork({ settings = {}, target = "predict
|
|
|
54
57
|
req.frame(event);
|
|
55
58
|
}
|
|
56
59
|
});
|
|
57
|
-
write({autoDetect:settings.autoDetect===true,pac:settings.pac||"",...(target
|
|
60
|
+
write({autoDetect:settings.autoDetect===true,pac:settings.pac||"",...(target !== "prediction" ? {target,timeoutMs} : {}),...(target === "api" ? {apiTargets} : {})});
|
|
58
61
|
const timer=setTimeout(()=>stop(failure("proxy_wpad_timeout")),timeoutMs);
|
|
59
62
|
let script;
|
|
60
63
|
try{if(signal?.aborted)cancelled();script=await ready;}catch(error){stop(error);throw error;}finally{clearTimeout(timer);signal?.removeEventListener("abort",cancelled);}
|
|
@@ -66,8 +69,10 @@ export async function startWindowsHttpNetwork({ settings = {}, target = "predict
|
|
|
66
69
|
const start=()=>{
|
|
67
70
|
if(started)return;started=true;
|
|
68
71
|
const host=options.hostname;
|
|
69
|
-
if(!allowedHosts.includes(host)||!String(options.path).startsWith("/")||String(options.path).startsWith("//"))throw failure("proxy_target_invalid");
|
|
72
|
+
if(!allowedHosts.includes(host)||!String(options.path).startsWith("/")||target !== "api" && String(options.path).startsWith("//"))throw failure("proxy_target_invalid");
|
|
70
73
|
if(target === "m365" && !String(options.path).startsWith("/api/v1/llmapi/")) throw failure("proxy_target_invalid");
|
|
74
|
+
const requestUrl = `https://${host}${options.port && Number(options.port) !== 443 ? `:${options.port}` : ""}${options.path}`;
|
|
75
|
+
if(target === "api" && !apiTargets.includes(requestUrl)) throw failure("proxy_target_invalid");
|
|
71
76
|
const headers=[];
|
|
72
77
|
for(const [name,value]of Object.entries(options.headers||{})){
|
|
73
78
|
if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/i.test(name))throw failure("proxy_headers_invalid");
|
|
@@ -81,7 +86,7 @@ export async function startWindowsHttpNetwork({ settings = {}, target = "predict
|
|
|
81
86
|
const rawLength=options.headers?.["content-length"];
|
|
82
87
|
const length=rawLength===undefined?(["GET","HEAD"].includes(options.method||"GET")?0:-1):Number(rawLength);
|
|
83
88
|
if(!Number.isSafeInteger(length)||length < -1)throw failure("proxy_upload_length_invalid");
|
|
84
|
-
requests.set(id,req);write({op:"request",id,url
|
|
89
|
+
requests.set(id,req);write({op:"request",id,url:requestUrl,method:options.method||"GET",headers:headerText,length});
|
|
85
90
|
};
|
|
86
91
|
const req=new Writable({highWaterMark:32*1024,autoDestroy:false,
|
|
87
92
|
write(chunk,_encoding,complete){
|
|
@@ -31,6 +31,7 @@ public static class CCDXPredictionNetwork {
|
|
|
31
31
|
static readonly JavaScriptSerializer json = new JavaScriptSerializer { MaxJsonLength=2*1024*1024 };
|
|
32
32
|
static IntPtr session;
|
|
33
33
|
static string target = "prediction";
|
|
34
|
+
static HashSet<string> apiTargets = new HashSet<string>(StringComparer.Ordinal);
|
|
34
35
|
static int requestTimeout = 30000;
|
|
35
36
|
class Work { public IntPtr handle; public ManualResetEventSlim ack = new ManualResetEventSlim(false); public BlockingCollection<byte[]> upload = new BlockingCollection<byte[]>(2); public bool cancelled; }
|
|
36
37
|
static void Check(bool ok) { if(!ok) throw new IOException("winhttp_" + Marshal.GetLastWin32Error()); }
|
|
@@ -77,7 +78,7 @@ public static class CCDXPredictionNetwork {
|
|
|
77
78
|
IntPtr connection=IntPtr.Zero;
|
|
78
79
|
try {
|
|
79
80
|
var uri=new Uri((string)data["url"]);
|
|
80
|
-
if(uri.Scheme!="https" || uri.
|
|
81
|
+
if(uri.Scheme!="https" || uri.UserInfo.Length!=0 || uri.Fragment.Length!=0 || (target=="api" ? !apiTargets.Contains(uri.AbsoluteUri) : (uri.Port!=443 || (target=="m365" ? (uri.Host!="df.loki.delve.office.com" || !uri.AbsolutePath.StartsWith("/api/v1/llmapi/",StringComparison.Ordinal)) : (uri.Host!="chatgpt.com"&&uri.Host!="ab.chatgpt.com"))))) throw new IOException("winhttp_target_invalid");
|
|
81
82
|
var method=(string)data["method"];
|
|
82
83
|
if(method!="GET"&&method!="POST"&&method!="HEAD"&&method!="PUT"&&method!="DELETE"&&method!="OPTIONS"&&method!="PATCH")throw new IOException("winhttp_method_invalid");
|
|
83
84
|
var headers=(string)data["headers"];
|
|
@@ -129,9 +130,10 @@ public static class CCDXPredictionNetwork {
|
|
|
129
130
|
try {
|
|
130
131
|
var initial=json.Deserialize<Dictionary<string,object>>(Console.ReadLine());
|
|
131
132
|
if(initial.ContainsKey("target")) target=(string)initial["target"];
|
|
132
|
-
if(target!="prediction"&&target!="m365")throw new IOException("winhttp_target_invalid");
|
|
133
|
-
if(target=="
|
|
134
|
-
|
|
133
|
+
if(target!="prediction"&&target!="m365"&&target!="api")throw new IOException("winhttp_target_invalid");
|
|
134
|
+
if(target=="api") { if(initial["apiTargets"] is string)throw new IOException("winhttp_target_invalid");foreach(object raw in (System.Collections.IEnumerable)initial["apiTargets"]) { var uri=new Uri((string)raw);if(uri.Scheme!="https"||uri.UserInfo.Length!=0||uri.Query.Length!=0||uri.Fragment.Length!=0)throw new IOException("winhttp_target_invalid");apiTargets.Add(uri.AbsoluteUri);if(apiTargets.Count>8)throw new IOException("winhttp_target_invalid"); }if(apiTargets.Count<1)throw new IOException("winhttp_target_invalid"); }
|
|
135
|
+
if(target!="prediction" && initial.ContainsKey("timeoutMs")) requestTimeout=(int)Math.Max(1000,Math.Min(int.MaxValue,Convert.ToInt64(initial["timeoutMs"])));
|
|
136
|
+
session=WinHttpOpen(target=="m365"?"CCDX Microsoft 365":target=="api"?"CCDX API":"CCDX native prediction",4,null,null,0);
|
|
135
137
|
Check(session!=IntPtr.Zero);Check(WinHttpSetTimeouts(session,10000,10000,requestTimeout,requestTimeout));
|
|
136
138
|
uint protocols=0x800;Check(WinHttpSetOption(session,84,ref protocols,4));
|
|
137
139
|
string pac=(string)initial["pac"];
|