codex-copilot-dx 1.2.16 → 1.2.18

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.
@@ -0,0 +1,91 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export const MODEL_PROTOCOLS = Object.freeze(["messages", "responses", "chat"]);
4
+ export const REASONING_EFFORTS = Object.freeze(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
5
+ const limits = ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_budget_min", "reasoning_budget_max"];
6
+ const flags = ["reasoning", "reasoning_required", "reasoning_adaptive", "tools", "parallel_tools", "streaming", "structured_output"];
7
+ export const CAPABILITY_FIELDS = Object.freeze([...limits, ...flags, "reasoning_efforts", "reasoning_format", "input_modalities", "web_search"]);
8
+ const object = value => value && typeof value === "object" && !Array.isArray(value);
9
+ export function validCapabilities(value) {
10
+ return object(value) && Object.entries(value).every(([key, item]) => {
11
+ if (limits.includes(key)) return Number.isSafeInteger(item) && item > 0 && item <= 100000000;
12
+ if (flags.includes(key)) return typeof item === "boolean";
13
+ if (key === "reasoning_format") return MODEL_PROTOCOLS.includes(item);
14
+ const choices = key === "reasoning_efforts" ? REASONING_EFFORTS : key === "input_modalities" ? ["text", "image", "audio", "video", "file"] : key === "web_search" ? MODEL_PROTOCOLS : null;
15
+ return choices && Array.isArray(item) && item.length <= choices.length && new Set(item).size === item.length && item.every(v => choices.includes(v));
16
+ }) && !(value.max_input_tokens && value.context_window && value.max_input_tokens > value.context_window)
17
+ && !(value.reasoning_budget_min && value.reasoning_budget_max && value.reasoning_budget_min > value.reasoning_budget_max);
18
+ }
19
+
20
+ // The identity excludes display names and catalog edits. A key/endpoint change
21
+ // invalidates deployment evidence without changing the public model route.
22
+ export function deploymentRevision(config, env = process.env) {
23
+ return createHash("sha256").update(JSON.stringify([config.base_url, config.endpoints, config.auth_header,
24
+ config.key_env ? [config.key_env, env[config.key_env] || ""] : config.secret_ref])).digest("hex").slice(0, 32);
25
+ }
26
+ export function deploymentModelId(source, model) {
27
+ return `ccdx/model-${BigInt("0x" + createHash("sha256").update(source + "\0" + model).digest("hex").slice(0, 24))}`;
28
+ }
29
+
30
+ // Interpret explicit fields only. A name or a working text reply is not evidence
31
+ // for a context size, reasoning mode, image input or native search.
32
+ export function catalogCapabilities(model) {
33
+ const caps = model?.capabilities || {}, window = caps.limits || {}, supports = caps.supports || {}, values = {};
34
+ const first = (...items) => items.find(value => value !== undefined && value !== null);
35
+ const candidate = {
36
+ context_window: first(model.context_window, window.max_context_window_tokens),
37
+ max_input_tokens: first(model.max_input_tokens, window.max_prompt_tokens, window.max_input_tokens),
38
+ max_output_tokens: first(model.max_output_tokens, window.max_output_tokens),
39
+ reasoning: first(typeof caps.reasoning === "boolean" ? caps.reasoning : undefined, supports.reasoning),
40
+ reasoning_efforts: first(model.reasoning_efforts, supports.reasoning_effort),
41
+ input_modalities: first(model.input_modalities, caps.input_modalities),
42
+ tools: supports.tools, parallel_tools: supports.parallel_tool_calls, streaming: supports.streaming,
43
+ structured_output: supports.structured_output, web_search: first(model.web_search, caps.web_search),
44
+ ...Object.fromEntries(["reasoning_required", "reasoning_adaptive", "reasoning_budget_min", "reasoning_budget_max", "reasoning_format"].map(key => [key, first(model[key], caps[key])])),
45
+ };
46
+ for (const [key, value] of Object.entries(candidate)) if (value !== undefined && validCapabilities({ [key]: value })) values[key] = value;
47
+ if (values.max_input_tokens > values.context_window) delete values.max_input_tokens;
48
+ if (values.reasoning_budget_min > values.reasoning_budget_max) { delete values.reasoning_budget_min;delete values.reasoning_budget_max; }
49
+ return values;
50
+ }
51
+
52
+ export function resolveModelCapabilities(model, { revision, checkedAt = null, builtin = false } = {}) {
53
+ const fields = {}, declared = builtin ? catalogCapabilities(model) : model.metadata?.deployment === revision ? model.metadata.values : {};
54
+ const put = (values, source, time) => { for (const [key, value] of Object.entries(values || {})) fields[key] = { value, source, checked_at: time }; };
55
+ put(declared, "catalog", builtin ? checkedAt : model.metadata?.checked_at || null);
56
+ put({ ...(model.context_window === undefined ? {} : { context_window: model.context_window }),
57
+ ...(model.reasoning_efforts === undefined ? {} : { reasoning_efforts: model.reasoning_efforts }) }, "manual", null);
58
+ put(model.capabilities, "manual", null);
59
+ const values = Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, field.value]));
60
+ if (values.reasoning === false) { delete values.reasoning_efforts;delete values.reasoning_adaptive;delete values.reasoning_required; }
61
+ const revisionId = createHash("sha256").update(JSON.stringify([revision, values])).digest("hex").slice(0, 16);
62
+ return { values, fields, revision: revisionId, stale: Boolean(model.metadata && model.metadata.deployment !== revision) };
63
+ }
64
+
65
+ export function claudeEffortsExpressible(values = {}) {
66
+ const levels = values.reasoning === false ? [] : values.reasoning_efforts || [];
67
+ const native = ["low", "medium", "high", "xhigh", "max"];
68
+ return levels.length > 0 && levels.every(value => native.includes(value)) && native.slice(0, Math.max(...levels.map(value => native.indexOf(value))) + 1).every(value => levels.includes(value));
69
+ }
70
+
71
+ export function constrainModelRequest(body, capability, protocol) {
72
+ const values = capability?.values || {}, outputKey = protocol === "messages" ? "max_tokens" : protocol === "responses" ? "max_output_tokens" : "max_completion_tokens";
73
+ let result = body;const applied = [];
74
+ if (values.max_output_tokens && Number.isFinite(body[outputKey]) && body[outputKey] > values.max_output_tokens) {
75
+ result = { ...result, [outputKey]: values.max_output_tokens };applied.push("output_limit");
76
+ }
77
+ const effort = protocol === "responses" ? body.reasoning?.effort : protocol === "messages" ? body.output_config?.effort : body.reasoning_effort;
78
+ if (effort !== undefined && (values.reasoning === false && effort !== "none" || values.reasoning_efforts && !values.reasoning_efforts.includes(effort))) {
79
+ throw Object.assign(new Error("This model does not declare the selected reasoning level. Choose a supported level."), { code: "ccdx_api_effort_unavailable", statusCode: 400 });
80
+ }
81
+ if (values.reasoning === false && body.thinking && body.thinking.type !== "disabled") {
82
+ throw Object.assign(new Error("Reasoning is disabled for this model."), { code: "ccdx_api_reasoning_unavailable", statusCode: 400 });
83
+ }
84
+ const budget = body.thinking?.budget_tokens;
85
+ if (Number.isFinite(budget) && (values.reasoning_budget_min && budget < values.reasoning_budget_min || values.reasoning_budget_max && budget > values.reasoning_budget_max
86
+ || applied.includes("output_limit") && Number.isFinite(result.max_tokens) && budget >= result.max_tokens)) {
87
+ throw Object.assign(new Error("Reasoning budget is outside this model's declared limits."), { code: "ccdx_api_reasoning_budget_invalid", statusCode: 400 });
88
+ }
89
+ if (values.tools === false && Array.isArray(body.tools) && body.tools.length) throw Object.assign(new Error("Tool calls are disabled for this model."), { code: "ccdx_api_tools_unavailable", statusCode: 400 });
90
+ return { body: result, applied };
91
+ }
@@ -10,15 +10,19 @@ import { markUpstreamHeaders } from "../stream-performance.mjs";
10
10
  import { createApiNetwork } from "./api-network.mjs";
11
11
  import { checkedApiKey } from "../api-secrets.mjs";
12
12
  import { transportErrorDetails } from "../operation-error.mjs";
13
+ import { catalogCapabilities, resolveModelCapabilities, deploymentRevision, constrainModelRequest } from "../model-capabilities.mjs";
14
+ import { codexModelEntry } from "../client-model-plan.mjs";
15
+ import { markRequestObservation } from "../stream-performance.mjs";
13
16
 
14
17
  const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
15
- export function apiCatalog(config) {
16
- return config.models.map(model => ({ id: model.id, name: model.id, publisher: "Unknown",
18
+ export function apiCatalog(config, env = process.env) {
19
+ return config.models.map(model => { const capability = resolveModelCapabilities(model, { revision: deploymentRevision(config, env) });return ({ id: model.id, name: model.id, publisher: "Unknown",
17
20
  supported_endpoints: model.protocols.map(api => paths[api]), model_picker_enabled: true, policy: { state: "enabled" },
18
- capabilities: { limits: { max_context_window_tokens: model.context_window }, supports: { reasoning_effort: model.reasoning_efforts || [] } } }));
21
+ capability, capabilities: { limits: { max_context_window_tokens: capability.values.context_window, max_output_tokens: capability.values.max_output_tokens },
22
+ supports: { reasoning_effort: capability.values.reasoning_efforts || [] } } }); });
19
23
  }
20
24
  export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork } = {}) {
21
- const catalog = apiCatalog(config), declarations = new Map(config.models.map(model => [model.id, model]));
25
+ const catalog = apiCatalog(config, env);
22
26
  const fingerprint = config.key_env ? createHash("sha256").update(env[config.key_env] || "").digest("hex") : "";
23
27
  const generation = parseInt(createHash("sha256").update(JSON.stringify(config) + fingerprint).digest("hex").slice(0, 8), 16);
24
28
  const profiles = Object.fromEntries(["messages", "responses", "chat"].map(protocol => [protocol, `api:${config.id}:${createHash("sha256").update(JSON.stringify({
@@ -55,6 +59,12 @@ export function createApiProvider({ config, secrets, env = process.env, platform
55
59
  headers["anthropic-version"] = "2023-06-01";
56
60
  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; }
57
61
  }
62
+ if (body && !options.countTokens) {
63
+ const capability = catalog.find(model => model.id === body.model)?.capability;
64
+ const constrained = constrainModelRequest(body, capability, api);
65
+ if (constrained.body !== body) { body = constrained.body;options = { ...options, bodyText: undefined }; }
66
+ markRequestObservation({ capability_revision: capability?.revision, capability_constraints: constrained.applied.join(",") || "none" });
67
+ }
58
68
  const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
59
69
  if (serialized !== undefined) headers["Content-Length"] = String(Buffer.byteLength(serialized));
60
70
  options.onUpstreamStart?.();
@@ -99,21 +109,13 @@ export function createApiProvider({ config, secrets, env = process.env, platform
99
109
  return {
100
110
  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)),
101
111
  codexCatalog(models) {
102
- return { ...models, models: config.models.filter(model => model.protocols.includes("responses")).map((model, priority) => ({
103
- slug: model.id, display_name: model.id, description: config.name, visibility: "list", supported_in_api: true, priority,
104
- default_reasoning_level: model.reasoning_efforts?.[0] || null, supported_reasoning_levels: (model.reasoning_efforts || []).map(effort => ({ effort, description: effort })),
105
- shell_type: "unified_exec", availability_nux: null, upgrade: null, additional_speed_tiers: [], service_tiers: [],
106
- // Neutral metadata for a native Responses API. Never borrow another model's instructions or capabilities.
107
- base_instructions: "", support_verbosity: false, default_verbosity: null, apply_patch_tool_type: null,
108
- supports_reasoning_summary_parameter: false, default_reasoning_summary: "none", truncation_policy: { mode: "bytes", limit: 10000 },
109
- context_window: model.context_window || null, max_context_window: model.context_window || null, experimental_supported_tools: [], input_modalities: ["text"],
110
- })) };
112
+ return { ...models, models: catalog.filter(model => model.supported_endpoints.includes(paths.responses)).map((model, priority) => codexModelEntry(model, { priority, name: config.name })) };
111
113
  },
112
114
  catalog: () => catalog,
113
115
  publicCatalog(allowed = []) { return { source: "configured", checkedAt: config.checked_at || null, upstreamHost: new URL(config.base_url).hostname,
114
116
  advertised: catalog.length, models: publicModelCatalog(catalog, { selectable: model => allowed.some(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)),
115
117
  clients: model => allowed.filter(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)) }).map(model => ({ ...model,
116
- auto_review_efforts: [...(declarations.get(model.id)?.reasoning_efforts || [])] })) }; },
118
+ capability: catalog.find(entry => entry.id === model.id)?.capability, auto_review_efforts: [...(catalog.find(entry => entry.id === model.id)?.capability.values.reasoning_efforts || [])] })) }; },
117
119
  async discover({ signal } = {}) {
118
120
  const response = await request(modelsUrl, undefined, { signal }, config.endpoints.responses ? "responses" : "messages");
119
121
  if (!response.ok) { await response.body?.cancel();throw accessError(`ccdx_api_catalog_http_${response.status}`, response.status === 401 || response.status === 403 ? response.status : 502); }
@@ -123,7 +125,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
123
125
  const ids = new Set();
124
126
  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); }
125
127
  // A catalog listing is not evidence that every model supports every API.
126
- return value.data.map(model => ({ id: model.id, protocols: Array.isArray(model.supported_endpoints)
128
+ return value.data.map(model => ({ id: model.id, ...(Object.keys(catalogCapabilities(model)).length ? { metadata: { values: catalogCapabilities(model), checked_at: new Date().toISOString(), deployment: deploymentRevision(config, env) } } : {}), protocols: Array.isArray(model.supported_endpoints)
127
129
  ? 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]) : [] }));
128
130
  },
129
131
  selectModel(_body, { upstreamModel }) { selected(upstreamModel, "responses");return { upstreamModel, forceResponses: true }; },
@@ -96,6 +96,9 @@ export function createResponsesHandler(options) {
96
96
  const now = options.now || Date.now;
97
97
 
98
98
  return async function handleResponses(req, res) {
99
+ let provider = options.provider || defaultGithubProvider;
100
+ let { modelRegistry, responsesFn, responsesCompactFn, chatCompletionsFn, autoReviewModelResolver, openAIModelEnv } = options;
101
+ let getCachedModelEndpointsFn = options.getCachedModelEndpointsFn || provider.client.getCachedModelEndpoints;
99
102
  const abort = createRequestAbort(req, res);
100
103
  let releaseRequest = () => {};
101
104
  let prepared = null;
@@ -203,6 +206,14 @@ export function createResponsesHandler(options) {
203
206
  releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
204
207
  abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
205
208
  parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
209
+ const selectedProvider = options.resolveProvider?.(parsed, req);
210
+ if (selectedProvider) {
211
+ provider = selectedProvider;modelRegistry = provider.registry;
212
+ responsesFn = provider.client.responses;responsesCompactFn = provider.client.responsesCompact;chatCompletionsFn = provider.client.chatCompletions;
213
+ getCachedModelEndpointsFn = provider.client.getCachedModelEndpoints;
214
+ autoReviewModelResolver = () => options.providerPreference?.(provider.id);
215
+ if (provider.id !== "github") openAIModelEnv = { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" };
216
+ }
206
217
  options.validateConversation?.(parsed, req.headers, provider);
207
218
  activeDeadline = now() + upstreamTimeoutMs;
208
219
  activeTimeoutReason = "responses_prepare_timeout";
@@ -416,6 +427,9 @@ export function createResponsesCompactHandler(options) {
416
427
  const now = options.now || Date.now;
417
428
 
418
429
  return async function handleResponsesCompact(req, res) {
430
+ let provider = options.provider || defaultGithubProvider;
431
+ let { modelRegistry, responsesFn, responsesCompactFn, chatCompletionsFn, autoReviewModelResolver, openAIModelEnv } = options;
432
+ let getCachedModelEndpointsFn = options.getCachedModelEndpointsFn || provider.client.getCachedModelEndpoints;
419
433
  const abort = createRequestAbort(req, res);
420
434
  let releaseRequest = () => {};
421
435
  let prepared = null;
@@ -475,6 +489,14 @@ export function createResponsesCompactHandler(options) {
475
489
  releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
476
490
  abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
477
491
  const parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
492
+ const selectedProvider = options.resolveProvider?.(parsed, req);
493
+ if (selectedProvider) {
494
+ provider = selectedProvider;modelRegistry = provider.registry;
495
+ responsesFn = provider.client.responses;responsesCompactFn = provider.client.responsesCompact;chatCompletionsFn = provider.client.chatCompletions;
496
+ getCachedModelEndpointsFn = provider.client.getCachedModelEndpoints;
497
+ autoReviewModelResolver = () => options.providerPreference?.(provider.id);
498
+ if (provider.id !== "github") openAIModelEnv = { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" };
499
+ }
478
500
  options.validateConversation?.(parsed, req.headers, provider);
479
501
  activeDeadline = now() + upstreamTimeoutMs;
480
502
  activeTimeoutReason = "responses_prepare_timeout";
@@ -326,8 +326,11 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
326
326
  attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
327
327
  observeContext(values) {
328
328
  if (finished || !values || typeof values !== "object") return;
329
- for (const key of Object.keys(context)) {
329
+ for (const key of [...Object.keys(context), "capability_revision", "capability_constraints"]) {
330
330
  const value = values[key];
331
+ if (["capability_revision", "capability_constraints"].includes(key)) {
332
+ if (typeof value === "string" && /^[a-z0-9_,]{1,80}$/.test(value)) context[key] = value;continue;
333
+ }
331
334
  if (Number.isSafeInteger(value) && value >= 0 && (key !== "context_window_tokens" || value > 0)) context[key] = value;
332
335
  }
333
336
  },