codex-copilot-dx 1.3.27 → 1.3.28

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.
@@ -2,6 +2,7 @@ import { modelReasoningEfforts } from "./provider-metadata.mjs";
2
2
  import { createHash } from "node:crypto";
3
3
  import { modelDisplayName } from "./model-display.mjs";
4
4
  import { claudeEffortPrefix } from "./model-capabilities.mjs";
5
+ import { claudeNativeModelHint } from "./claude-app-contract.mjs";
5
6
 
6
7
  const EFFORTS = ["low", "medium", "high", "xhigh", "max"];
7
8
 
@@ -19,7 +20,7 @@ function desktopModelId(id) {
19
20
  return `ccdx/claude-compatible-${BigInt(`0x${digest}`).toString(10)}`;
20
21
  }
21
22
 
22
- export function claudeModelEntries(models, { desktopAliases = false } = {}) {
23
+ export function claudeModelEntries(models, { desktopAliases = false, appContract } = {}) {
23
24
  const ids = new Set(), upstreamIds = new Set(models.map(model => model.id));
24
25
  return models.map(model => {
25
26
  const name = model.client_id || (desktopAliases ? desktopModelId(model.id) : claudeClientModelId(model.id));
@@ -28,7 +29,8 @@ export function claudeModelEntries(models, { desktopAliases = false } = {}) {
28
29
  const advertised = model.capability?.values.reasoning === false ? [] : model.capability?.values.reasoning_efforts || modelReasoningEfforts(model);
29
30
  const prefix = /^mythos-ccdx-\d+$/.test(name) ? claudeEffortPrefix(model.capability?.values) : [];
30
31
  const maxEffort = prefix.at(-1) || EFFORTS.filter(value => advertised?.includes(value)).at(-1);
31
- return { name, ...(model.display_name || name !== claudeClientModelId(model.id) ? { labelOverride: modelDisplayName(model) } : {}),
32
+ const hint = claudeNativeModelHint(model.capability?.values, appContract);
33
+ return { name, ...(hint || {}), ...(model.display_name || name !== claudeClientModelId(model.id) ? { labelOverride: modelDisplayName(model) } : {}),
32
34
  ...(model.capability?.values.context_window >= 1000000 ? { supports1m: true } : {}), ...(maxEffort ? { maxEffort } : {}) };
33
35
  });
34
36
  }
@@ -56,6 +56,9 @@ export const MANAGED_COMMANDS = [
56
56
  )
57
57
  ),
58
58
  command("source list", "List registered model sources", read),
59
+ command("source import", "Preview supplied CCDX, CC Switch or Magpie API metadata; apply one explicitly", {
60
+ ...read, "--file": "value", "--select": "integer", "--apply": "flag", "--key-stdin": "flag", ...confirm,
61
+ }),
59
62
  command("source add", "Save an API and read its model catalog", {
60
63
  "--file": "value",
61
64
  "--key-stdin": "flag",
@@ -176,6 +179,7 @@ export const MANAGED_COMMANDS = [
176
179
  "--failed": "flag",
177
180
  "--app": "value",
178
181
  "--source": "value",
182
+ "--purpose": "purpose",
179
183
  "--limit": "integer",
180
184
  }),
181
185
  command("requests show <request>", "Show a retained request and its original diagnostic fields", read),
@@ -185,6 +189,7 @@ export const MANAGED_COMMANDS = [
185
189
  "--scope": "scope",
186
190
  "--provider": "value",
187
191
  "--model": "value",
192
+ "--purpose": "purpose",
188
193
  "--days": "value",
189
194
  "--from": "value",
190
195
  "--to": "value",
@@ -226,6 +231,7 @@ function optionsFor(args, definition) {
226
231
  if (type === "format" && !["table", "plain", "json"].includes(value))
227
232
  throw new Error("Format must be table, plain or json");
228
233
  if (type === "scope" && !["run", "all"].includes(value)) throw new Error("Scope must be run or all");
234
+ if (type === "purpose" && !["conversation", "diagnostic", "compatibility", "unknown"].includes(value)) throw new Error("Purpose must be conversation, diagnostic, compatibility or unknown");
229
235
  if (type === "integer" && (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 100))
230
236
  throw new Error("Limit must be an integer from 1 to 100");
231
237
  values[key] = type === "integer" ? Number(value) : value;
@@ -276,7 +282,7 @@ export function parseManagedCommand(args) {
276
282
 
277
283
  const extras = {
278
284
  source:
279
- "Status reads local/cached evidence. check/--refresh may contact the source; no inference.\nSource access grants do not select client models. Disable previews affected clients.\nGitHub login and company-account selection are source-specific.\nChoose visible models and defaults with app <app> models --edit.",
285
+ "Status reads local/cached evidence. check/--refresh may contact the source; no inference.\nsource import --file FILE previews supplied metadata. --select N --apply saves one source using private key input; no client access is granted.\nSource access grants do not select client models. Disable previews affected clients.\nGitHub login and company-account selection are source-specific.\nChoose visible models and defaults with app <app> models --edit.",
280
286
  app: "Configured is not App adoption or process liveness. Unknown stays unknown.\nmodels shows the selected plan; source <id> models shows the upstream catalog.\nsetup/remove changes integration setup; pause/resume retains credentials.\nsync --preview shows the model/configuration plan, not a byte-level file diff.\nNo client program is force-restarted.",
281
287
  config:
282
288
  "Only service and terminal preferences are in scope. Browser appearance stays in WebUI.\nReset keeps accounts, keys, model plans and chats and stores a pre-reset backup.\nSaved and effective values can differ; restart requirements remain explicit.",
@@ -285,7 +291,7 @@ const extras = {
285
291
  status:
286
292
  "Default interactive status is brief; --details retains the complete diagnostic view.\nThe installed package version can differ from the running service.\nA listening gateway does not prove upstream model access.",
287
293
  usage:
288
- "Default usage includes all recorded usage. Filter it with --provider, --model and --days 1..365|all, or --from/--to YYYY-MM-DD.\nDates use --time-zone (UTC by default). Source-qualified models use 'source / model'.\n--scope run reads the running service and supports only --provider.\nGemini usage includes Antigravity Copilot and native Google responses. Missing upstream counts stay unknown; historical missing usage is not reconstructed.\nUsage records are not billed request counts. Cache hit is a token-reuse estimate.",
294
+ "Default usage includes all recorded usage. Filter it with --provider, --model, --purpose and --days 1..365|all, or --from/--to YYYY-MM-DD.\nPurpose: conversation, diagnostic, compatibility or unknown. Older records without a purpose remain unknown; every purpose stays in default totals.\nDates use --time-zone (UTC by default). Source-qualified models use 'source / model'.\n--scope run reads the running service and supports only --provider.\nGemini usage includes Antigravity Copilot and native Google responses. Missing upstream counts stay unknown; historical missing usage is not reconstructed.\nUsage records are not billed request counts. Cache hit is a token-reuse estimate.",
289
295
  doctor:
290
296
  "Default checks are read-only. Explicit online/compatibility checks and owned repairs have separate options.",
291
297
  update:
@@ -12,6 +12,8 @@ import { hiddenQuestion } from "./cli-secret.mjs";
12
12
  import { readBoundedFileSync } from "./bounded-file.mjs";
13
13
  import { deploymentModelId } from "./model-capabilities.mjs";
14
14
  import { TERMINAL_COLOR_THEMES } from "./terminal-colors.mjs";
15
+ import { previewSourceImport } from "./source-import.mjs";
16
+ import { readAccessSettings } from "./access-settings.mjs";
15
17
 
16
18
  async function readSecretInput(input) {
17
19
  const chunks = [];let bytes = 0;
@@ -115,20 +117,20 @@ export async function runManagementCommand(command, options = {}) {
115
117
  const found = rows.find(row => row.request_id === ids.request);if (!found) throw new Error("Request not retained. No full-history lookup is available.");return print(found);
116
118
  }
117
119
  rows = rows.filter(row => (!flags.active || row.active) && (!flags.failed || row.state !== "cancelled" && (row.state === "failed" || row.error))
118
- && (!flags.source || row.provider === flags.source) && (!flags.app || (flags.app === "codex" ? ["codex", "codex_app", "codex_cli"].includes(row.application) : row.application === (flags.app === "antigravity" ? "gemini_app" : CLI_CLIENTS[flags.app])))).slice(-(flags.limit || 20));
120
+ && (!flags.purpose || (row.purpose || "unknown") === flags.purpose) && (!flags.source || row.provider === flags.source) && (!flags.app || (flags.app === "codex" ? ["codex", "codex_app", "codex_cli"].includes(row.application) : row.application === (flags.app === "antigravity" ? "gemini_app" : CLI_CLIENTS[flags.app])))).slice(-(flags.limit || 20));
119
121
  return print(flags.format === "json" ? rows : rows.map(row => ({ ...row, state_label: terminalRequestState(row) })), [["request_id", "Request"], ["application", "Client"], ["provider", "Source"], ["model", "Model"], ["route", "Route"], ["state_label", "State"]]);
120
122
  }
121
123
  if (group === "usage") {
122
124
  if (flags.scope === "run") {
123
- if (flags.model || flags.days || flags.from || flags.to || flags.time_zone) throw new Error("Model and date filters require --scope all; current-run totals support only --provider.");
125
+ if (flags.purpose || flags.model || flags.days || flags.from || flags.to || flags.time_zone) throw new Error("Model and date filters require --scope all; current-run totals support only --provider.");
124
126
  const usage = (await readStatus()).data.runtime_usage;
125
127
  if (!usage) throw new Error("Current-run usage is unavailable.");
126
128
  return print(flags.provider ? usage.by_provider?.[flags.provider] || { records: 0 } : usage);
127
129
  }
128
130
  const { summarizeUsageLogs } = await import("./usage-store.mjs");
129
131
  const { createUsageQuery } = await import("./usage-query.mjs");
130
- const selection = createUsageQuery({ provider: flags.provider, model: flags.model, days: flags.days, from: flags.from, to: flags.to, timeZone: flags.time_zone });
131
- const filtered = selection.filters.model || selection.filters.from || selection.filters.to;
132
+ const selection = createUsageQuery({ provider: flags.provider, model: flags.model, purpose: flags.purpose, days: flags.days, from: flags.from, to: flags.to, timeZone: flags.time_zone });
133
+ const filtered = selection.filters.purpose || selection.filters.model || selection.filters.from || selection.filters.to;
132
134
  const summary = await summarizeUsageLogs(undefined, { ...(flags.provider ? { provider: flags.provider } : {}), ...(filtered ? { recordFilter: selection.matches } : {}) });
133
135
  summary.filters = selection.filters;
134
136
  if (flags.format === "json") return print(summary);
@@ -241,7 +243,7 @@ export async function runManagementCommand(command, options = {}) {
241
243
  return print({ id: ids.app, access: client.enabled ? clientSetup(client) === "Paused" ? "Paused" : "Enabled" : "Disabled", setup: view.clients.find(row => row.id === id)?.setup || clientSetup(client),
242
244
  selected_models: Array.isArray(client.deployments) ? client.deployments.length : modelPlan?.models.length ?? null, unavailable_selection: (modelPlan?.unavailable || []).filter(model => !modelPlan?.available.some(candidate => candidate.source === model.source && candidate.id === model.id)),
243
245
  app_adoption: view.clients.find(row => row.id === id)?.active > 0 ? "Active gateway request observed; process liveness not checked" : observed ? `Gateway request observed${observed.at || observed.time ? ` at ${observed.at || observed.time}` : ""}; process liveness not checked` : client.observed_at ? `Gateway request observed at ${client.observed_at}; process liveness not checked` : "Not observed",
244
- active: view.clients.find(row => row.id === id)?.active ?? null, ...(id === "codex" && flags.details ? { features: details, chatgpt_sign_in: "Managed by Codex; not inferred from GitHub credentials" } : {}) });
246
+ active: view.clients.find(row => row.id === id)?.active ?? null, ...(id.startsWith("claude_") && flags.details ? { capability_support: modelPlan?.support, capability_adoption: client.capability_adoption, capability_sync: modelPlan?.sync } : {}), ...(id === "codex" && flags.details ? { features: details, chatgpt_sign_in: "Managed by Codex; not inferred from GitHub credentials" } : {}) });
245
247
  }
246
248
  if (action === "models" && !flags.edit) {
247
249
  if (flags.format === "json") return print(modelPlan);
@@ -313,6 +315,24 @@ export async function runManagementCommand(command, options = {}) {
313
315
  const result = await save(imageOnly ? { operation: "image_model", id: "codex", model: body.image_model, client_revision: client.revision } : body);return print({ client: ids.app, setup: getClient(result, id).setup, saved: true, app_adoption: "Not verified" });
314
316
  }
315
317
  if (group !== "source") throw new Error("Unknown management command.");
318
+ if (action === "import") {
319
+ if (!flags.file) throw new Error("Supply one explicit JSON file with --file.");
320
+ const preview = previewSourceImport(readFile(), readAccessSettings(options).apis);
321
+ if (!flags.apply || flags.preview) return print(preview);
322
+ const selected = preview.drafts[(flags.select || 0) - 1];
323
+ if (!selected) throw new Error("Review the preview, then use --select NUMBER --apply for one source.");
324
+ output.write(print(selected) + "\n");
325
+ const graph = await connection();requireManagement();
326
+ if (graph.providers.some(source => source.name?.trim().toLowerCase() === selected.config.name.trim().toLowerCase())) throw new Error("A source with this name exists. Edit its settings explicitly, or rename the imported draft.");
327
+ let key;
328
+ if (!selected.config.key_env) {
329
+ if (!flags.key_stdin) throw new Error("Use --key-stdin or a configured key_env; foreign credential values are not copied.");
330
+ key = await readSecretInput(input);
331
+ }
332
+ await confirm("Save this one API without granting client access or selecting models?");
333
+ const result = await save({ operation: "save_api", config: selected.config, allowed: [], ...(key ? { key } : {}) });key = undefined;
334
+ return print({ saved: true, source: result.providers.find(source => source.name === selected.config.name)?.id, authorized_clients: [] });
335
+ }
316
336
  let graph = await connection();
317
337
  if (!flags.preview && (flags.edit || ["add", "edit", "enable", "disable", "remove"].includes(action))) requireManagement();
318
338
  if (action === "list") return print(graph.providers.map(source => ({ id: source.id, name: source.name, enabled: source.enabled, key_saved: source.builtin ? undefined : source.key_saved })), [["id", "ID"], ["name", "Source"], ["enabled", "Enabled"]]);
@@ -325,7 +345,7 @@ export async function runManagementCommand(command, options = {}) {
325
345
  if (action === "models") return print({ source: id, evidence: "Saved API model selection; access not checked", models: source.models });
326
346
  const diagnostics = await request({ path: "providers" }), observed = diagnostics.providers.find(provider => provider.id === id);
327
347
  return print({ id, name: source.name, saved_enabled: source.enabled, runtime_state: observed?.state || "Not observed", credentials: source.builtin ? observed?.auth : { key_saved: source.key_saved },
328
- catalog: observed?.models || source.discovery || { count: source.models?.length ?? null, source: "configured" }, access: "Not inferred from saved credentials or configuration", diagnostic: observed?.catalog_diagnostic || null });
348
+ catalog: observed?.models || source.discovery || { count: source.models?.length ?? null, source: "configured" }, health: observed?.health || source.discovery?.health || null, access: "Not inferred from saved credentials or configuration", diagnostic: observed?.catalog_diagnostic || null });
329
349
  }
330
350
  if (action === "check" || action === "models" && flags.refresh) {
331
351
  if (!source.enabled || id === "m365" && graph.m365_state === "disabled") throw new Error("Source is disabled; it was not enabled automatically.");
@@ -105,6 +105,7 @@ export function createConnectionClientSync({ options, corePort, configureCodex,
105
105
  client: id,
106
106
  profileName: "CCDX",
107
107
  desktopAliases: id === "claude_app" && source?.id.startsWith("api_"),
108
+ appContract: capabilitySupport.app_contract,
108
109
  disableExperimentalBetas: m365Only,
109
110
  desktopManaged: id === "claude_app" ? desktopManaged : false,
110
111
  baseUrl: `http://127.0.0.1:${corePort}/anthropic`,
@@ -1,3 +1,4 @@
1
+ import { previewSourceImport } from "./source-import.mjs";
1
2
  import { prepareSourceAccess, accessError, CLIENT_IDS } from "./access-settings.mjs";
2
3
  import { publicModelCatalog } from "./provider-metadata.mjs";
3
4
  import { createConnectionPolicy } from "./connection-policy.mjs";
@@ -138,6 +139,10 @@ export function createConnectionManagement({ binding, catalogRefresh, save, disc
138
139
  if (binding("codex").enabled) void memoryModel.refresh();
139
140
  return snapshot();
140
141
  }
142
+ if (validObject(input, ["operation", "content"]) && input.operation === "preview_import") {
143
+ try { return previewSourceImport(input.content, getSettings().apis); }
144
+ catch (error) { throw accessError(/^ccdx_import_[a-z_]+$/.test(error.message) ? error.message : "ccdx_import_metadata_invalid"); }
145
+ }
141
146
  if (validObject(input, ["operation", "id"]) && input.operation === "source_catalog") {
142
147
  if (!["github", "m365", ...getSettings().apis.map(api => api.id)].includes(input.id))
143
148
  throw accessError("ccdx_connections_action_invalid");
@@ -176,7 +176,7 @@ export function createConnectionPolicy({ validObject, binding, catalogRefresh, s
176
176
  source: getSource,
177
177
  enabled,
178
178
  names,
179
- desktopEffortAliases: capabilitySupport.app,
179
+ desktopEffortAliases: capabilitySupport.app && capabilitySupport.app_aliases !== false,
180
180
  });
181
181
  if (c.default_model && !compiled.routes.has(c.default_model))
182
182
  throw accessError("ccdx_api_model_unavailable");
@@ -233,7 +233,7 @@ export function createConnectionPolicy({ validObject, binding, catalogRefresh, s
233
233
  binding: c,
234
234
  source: getSource,
235
235
  enabled,
236
- desktopEffortAliases: capabilitySupport.app,
236
+ desktopEffortAliases: capabilitySupport.app && capabilitySupport.app_aliases !== false,
237
237
  });
238
238
  const shared =
239
239
  input.id === "codex"
@@ -6,7 +6,7 @@ import { currentRequestContext } from "./request-context.mjs";
6
6
 
7
7
  export function createConnectionRouting({ legacy, legacyClaudeAccess, isManaged, getSettings, binding, plan, permitted, getSource,
8
8
  resolveDeployment, codexAccessMode, codexRequiresKey, requireCodexKey, identities, track, guardConversation, messagesTransfer,
9
- acquireClaudeRequest, privacy, env, log, lastClients }) {
9
+ acquireClaudeRequest, privacy, env, log, lastClients, capabilitySupport }) {
10
10
  const handlers = new Map();
11
11
  function requireSource(clientId, id) {
12
12
  if (!permitted(clientId, id)) throw accessError("ccdx_client_source_disabled", 503);
@@ -152,6 +152,7 @@ export function createConnectionRouting({ legacy, legacyClaudeAccess, isManaged,
152
152
  log,
153
153
  performance: legacy.claudePerformance,
154
154
  desktopAliases: id === "claude_app",
155
+ appContract: id === "claude_app" ? capabilitySupport?.app_contract : undefined,
155
156
  messagesSystemMode: id === "claude_app" ? "legacy" : "passthrough",
156
157
  resolveRequest(body) {
157
158
  const record = resolveDeployment(id, body.model),
@@ -30,6 +30,7 @@ import { createMessagesHistoryTransfer } from "./messages-history-transfer.mjs";
30
30
  import { compileClientModels } from "./client-model-plan.mjs";
31
31
  import { currentRequestContext } from "./request-context.mjs";
32
32
  import { inspectClaudeCapabilitySupport } from "./claude-capability-config.mjs";
33
+ import { inspectClaudeAppContract, watchClaudeAppContract } from "./claude-app-contract.mjs";
33
34
  import { deploymentModelId, deploymentRevision } from "./model-capabilities.mjs";
34
35
  import { m365Paths } from "./m365-settings.mjs";
35
36
 
@@ -45,6 +46,7 @@ export function createConnectionRuntime({
45
46
  restoreClaude = restoreClaudeClients,
46
47
  configureCodex = configureCodexApi,
47
48
  inspectDesktop = inspectClaudeDesktopPolicy,
49
+ inspectAppContract = inspectClaudeAppContract,
48
50
  clientAccessChanged,
49
51
  preserveClientConfiguration,
50
52
  clientVersionsSnapshot,
@@ -86,6 +88,20 @@ export function createConnectionRuntime({
86
88
  onState: (id, state) => (state ? discoveries.set(id, state) : discoveries.delete(id)),
87
89
  });
88
90
  const capabilitySupport = inspectClaudeCapabilitySupport(options);
91
+ let capabilityFlight = null, capabilityWatch = null;
92
+ const refreshClientCapabilities = ({ sync = true } = {}) => {
93
+ if(closed||!managed||!binding("claude_app").enabled||!plan("claude_app").models.length)return Promise.resolve(structuredClone(capabilitySupport));
94
+ if (capabilityFlight) return capabilityFlight;
95
+ capabilityFlight = inspectAppContract(options).then(async contract => {
96
+ if(closed)return;
97
+ const next=inspectClaudeCapabilitySupport({...options,appContract:contract});
98
+ const changed=capabilitySupport.app_contract?.fingerprint!==contract.fingerprint||capabilitySupport.app_contract?.installation!==contract.installation||capabilitySupport.app_version!==next.app_version||capabilitySupport.app!==next.app;
99
+ await enqueue(()=>{Object.assign(capabilitySupport,next);if(changed){plans.delete("claude_app");plans.delete("claude_code")}});
100
+ if(changed&&sync&&managed)await clientSync.syncClients(["claude_app","claude_code"]);
101
+ return structuredClone(capabilitySupport);
102
+ }).finally(()=>{capabilityFlight=null});
103
+ return capabilityFlight;
104
+ };
89
105
  let operations = 0;
90
106
  const identities = () => (keys ||= readClientGatewayKeys(options));
91
107
  const enabled = id =>
@@ -180,7 +196,7 @@ export function createConnectionRuntime({
180
196
  ["m365", "Microsoft 365"],
181
197
  ...settings.apis.map(api => [api.id, api.name]),
182
198
  ]),
183
- desktopEffortAliases: capabilitySupport.app,
199
+ desktopEffortAliases: capabilitySupport.app && capabilitySupport.app_aliases !== false,
184
200
  });
185
201
  plans.set(id, { binding: selected, stamps, value });
186
202
  return value;
@@ -259,7 +275,7 @@ export function createConnectionRuntime({
259
275
  clientRevision, editable, syncClients, clientAccessChanged, setup, secrets, lifecycle, retire, memoryModel, enqueue, catalogVisibility });
260
276
  const { requireSource, methods: routing } = createConnectionRouting({ legacy, legacyClaudeAccess, isManaged: () => managed,
261
277
  getSettings: () => settings, binding, plan, permitted, getSource, resolveDeployment, codexAccessMode, codexRequiresKey, requireCodexKey,
262
- identities, track, guardConversation, messagesTransfer, acquireClaudeRequest, privacy, env, log, lastClients });
278
+ identities, track, guardConversation, messagesTransfer, acquireClaudeRequest, privacy, env, log, lastClients, capabilitySupport });
263
279
 
264
280
 
265
281
  async function applyCatalog(id, models, revision, checkedAt, active) {
@@ -358,6 +374,7 @@ export function createConnectionRuntime({
358
374
  ),
359
375
  privacy,
360
376
  busy: () => privacy.busy() ||
377
+ Boolean(capabilityFlight) ||
361
378
  operations > 0 ||
362
379
  lifecycle.busy() ||
363
380
  clientSync.busy() ||
@@ -365,11 +382,15 @@ export function createConnectionRuntime({
365
382
  legacy.snapshot().m365.account_change_in_flight === true ||
366
383
  legacy.snapshot().m365.state === "checking",
367
384
  syncClients,
385
+ refreshClientCapabilities,
368
386
  manageConnections: management.manageConnections,
369
387
  imageModels,
370
388
  async start() {
389
+ const capabilities = refreshClientCapabilities({sync:false});
390
+ capabilityWatch ||= watchClaudeAppContract({ ...options, onChange: refreshClientCapabilities });
371
391
  if (binding("codex").enabled) void memoryModel.refresh();
372
392
  const old = legacy.start();
393
+ await capabilities;
373
394
  if (managed) await syncClients();
374
395
  const result = await old;
375
396
  if (managed) await syncClients();
@@ -377,6 +398,7 @@ export function createConnectionRuntime({
377
398
  return result;
378
399
  },
379
400
  async refresh() {
401
+ await refreshClientCapabilities();
380
402
  const result = await Promise.allSettled([
381
403
  !managed || settings.providers.m365 ? legacy.refresh() : Promise.resolve(),
382
404
  refreshApis(),
@@ -403,6 +425,8 @@ export function createConnectionRuntime({
403
425
  action: management.action,
404
426
  async close() {
405
427
  closed = true;
428
+ capabilityWatch?.close();
429
+ await capabilityFlight;
406
430
  privacy.close();
407
431
  await memoryModel.close();
408
432
  await catalogRefresh.close();
@@ -38,6 +38,12 @@ export function createConnectionView({ legacy, env, binding, plan, getSource, en
38
38
  return {
39
39
  ...base,
40
40
  revision,
41
+ ...(id.startsWith("claude_") ? { capability_adoption: (() => {
42
+ const rows = legacy.claudePerformance?.snapshot?.().recent_requests || [];
43
+ const observed = rows.findLast(row => row.application === id && row.context?.reasoning_effort_sent);
44
+ return observed ? { state: "effort_observed", effort: observed.context.reasoning_effort_sent, source: observed.provider, model: observed.model, request_id: observed.request_id, at: observed.at }
45
+ : { state: "not_observed" };
46
+ })() } : {}),
41
47
  model_plan: {
42
48
  ...(id === "codex" ? { image: imageModels() } : {}),
43
49
  default_model: compiled.defaultModel,
@@ -117,7 +123,9 @@ export function createConnectionView({ legacy, env, binding, plan, getSource, en
117
123
  },
118
124
  ...config.apis.map(api => {
119
125
  const { secret_ref, ...publicApi } = api,
120
- revision = compact ? null : deploymentRevision(api, env);
126
+ revision = compact ? null : deploymentRevision(api, env),
127
+ health = compact ? null : getSource(api.id)?.health?.(),
128
+ cooling = health && Object.values(health).some(item => item.state !== "ready");
121
129
  return {
122
130
  ...(compact ? { id: api.id, name: api.name, enabled: api.enabled } : publicApi),
123
131
  ...summary(api),
@@ -129,7 +137,7 @@ export function createConnectionView({ legacy, env, binding, plan, getSource, en
129
137
  api.models.map(model => [model.id, modelDisplay.get(api.id, revision, model.id)])
130
138
  ),
131
139
  }),
132
- discovery: discoveries.get(api.id) || null,
140
+ discovery: cooling ? { ...discoveries.get(api.id), health } : discoveries.get(api.id) || null,
133
141
  builtin: false,
134
142
  key_saved: api.key_env ? Boolean(env[api.key_env]) : Boolean(secret_ref),
135
143
  };
@@ -288,6 +296,7 @@ export function createConnectionView({ legacy, env, binding, plan, getSource, en
288
296
  enabled: true,
289
297
  generation: old?.generation || source?.registry.generation || 1,
290
298
  state: old?.state || "configured",
299
+ ...(source?.health ? { health: source.health() } : {}),
291
300
  auth: old?.auth || { state: "saved", token_cached: false },
292
301
  selection: {
293
302
  codex: clients.some(client => client.id === "codex"),
@@ -62,6 +62,7 @@
62
62
  const response = await fetch("/_ccdx/ui/connections", { method: input ? "POST" : "GET", headers: { "X-CCDX-Dashboard": "1", ...(input ? { "Content-Type": "application/json" } : {}) },
63
63
  cache: "no-store", signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(35000)]) : AbortSignal.timeout(35000), ...(input ? { body: JSON.stringify(input) } : {}) });
64
64
  const result = await response.json();if (!response.ok) throw new Error(result.error || "ccdx_connections_action_failed");
65
+ if (input?.operation === "preview_import" && Array.isArray(result.drafts)) return result;
65
66
  if (result.source !== "connections" || !Array.isArray(result.providers) || !Array.isArray(result.clients)) throw new Error("ccdx_connections_unavailable");return result;
66
67
  }
67
68
  function panels(which = "list") {
@@ -83,6 +84,7 @@
83
84
  const row = node("div", undefined, "connection-row"), info = node("div"), actions = node("div", undefined, "connection-actions");info.append(node("h3", provider.enabled ? format("enable_service") : provider.name));
84
85
  if (!provider.builtin) info.append(node("p", provider.base_url, "hint"));
85
86
  if (provider.enabled) {
87
+ if (provider.discovery?.health) { const notice = node("p", undefined, "hint");words(notice, "source_cooling");info.append(notice); }
86
88
  if (provider.discovery?.state === "stale") { const warning = node("p", undefined, "hint");words(warning, "cap_catalog_stale");warning.append(" ", provider.discovery.code);info.append(warning); }
87
89
  if (!provider.builtin) actions.append(button("api_manage", () => editApi(provider)));
88
90
  const toggle = node("input");toggle.type = "checkbox";toggle.checked = true;toggle.setAttribute("role", "switch");toggle.setAttribute("aria-label", format("api_disable_source") + " " + provider.name);
@@ -201,9 +203,9 @@
201
203
  const advanced = node("details"), summary = node("summary");words(summary, "cap_manual");advanced.append(summary);detail.append(advanced);
202
204
  const note = node("p", undefined, "hint");words(note, "cap_metadata_scope");advanced.append(note);
203
205
  const fields = node("div", undefined, "connection-fields");
204
- const numeric = ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_budget_min", "reasoning_budget_max"];
206
+ const numeric = ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_budget_min", "reasoning_budget_max", "max_tool_definitions"];
205
207
  const flags = ["reasoning", "reasoning_required", "reasoning_adaptive", "tools", "parallel_tools", "streaming", "structured_output", "mid_conversation_system"];
206
- const arrays = ["reasoning_efforts", "thinking_modes", "input_modalities", "web_search"];
208
+ const arrays = ["reasoning_efforts", "thinking_modes", "input_modalities", "web_search", "supported_parameters"];
207
209
  for (const key of [...numeric, ...flags, ...arrays, "reasoning_format"]) {
208
210
  const label = node("label"), title = node("span");words(title, "cap_field_" + key);label.append(title);
209
211
  let input;
@@ -222,7 +224,7 @@
222
224
  words(status, fresh ? "cap_catalog_" + (model.metadata.state || "reported") : "cap_unknown");
223
225
  if (fresh && model.metadata.checked_at) status.append(" · ", new Date(model.metadata.checked_at).toLocaleString());
224
226
  body.replaceChildren();
225
- for (const key of ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_efforts", "reasoning_adaptive", "tools", "input_modalities", "web_search"]) {
227
+ for (const key of ["context_window", "max_input_tokens", "max_output_tokens", "max_tool_definitions", "supported_parameters", "reasoning_efforts", "reasoning_adaptive", "tools", "input_modalities", "web_search"]) {
226
228
  const row = node("tr"), label = node("th");words(label, ({ reasoning_efforts: "cap_reasoning", input_modalities: "cap_input_types", web_search: "cap_search" })[key] || "cap_field_" + key);
227
229
  const value = values[key], text = key === "reasoning_efforts" ? reasoningText(values) : key === "web_search" ? searchText(values)
228
230
  : value === undefined ? format("cap_unknown") : typeof value === "boolean" ? format(value ? "cap_supported" : "cap_unsupported") : Array.isArray(value) ? value.join(" / ") || format("cap_unsupported") : count(value);
@@ -253,6 +255,10 @@
253
255
  if (preview?.image?.selected_model) { const image = node("p");image.textContent = `${format("image_model")}: ${preview.image.selected_model}`;result.append(image); }
254
256
  const note = node("p", undefined, "hint");words(note, "cap_preview_scope");result.append(note);
255
257
  const sync = preview?.shared || c.model_plan?.sync;
258
+ if (editingClient === "claude_app" && c.model_plan?.support?.app_contract?.status === "verified") {
259
+ const contract = node("p", undefined, "hint");words(contract, "cap_contract_checked", { version: c.model_plan.support.app_version });result.append(contract);
260
+ if (c.capability_adoption?.state === "effort_observed") { const observation = node("p", undefined, "hint");words(observation, "cap_effort_observed", { effort: c.capability_adoption.effort });result.append(observation); }
261
+ }
256
262
  if (c.credential_state === "encrypted_unverified") { const kept = node("p", undefined, "hint");words(kept, "client_key_encrypted_kept");result.append(kept); }
257
263
  if (sync) { const status = node("p", undefined, "hint");words(status, "cap_sync_" + sync.state);result.append(status);
258
264
  for (const limitation of sync.limitations || []) { const line = node("p", undefined, "hint");words(line, "cap_limit_" + limitation.code);if (limitation.model) line.prepend(limitation.model + ": ");result.append(line); }
@@ -508,6 +514,30 @@
508
514
  impact_revision: disableRevision,
509
515
  replacements: Object.fromEntries([...el("connection-replacements").querySelectorAll("select")].map(select => [select.name, select.value || null])) }); });
510
516
  el("connection-add").addEventListener("click", () => { if (data) editApi(); });
517
+ el("connection-import").addEventListener("click", () => { if (data && !busy) el("connection-import-file").click(); });
518
+ el("connection-import-file").addEventListener("change", async event => {
519
+ const file = event.target.files?.[0];event.target.value = "";if (!file) return;
520
+ const preview = el("connection-import-preview");preview.hidden = true;preview.replaceChildren();
521
+ if (file.size > 256 * 1024) { message("ccdx_import_size_invalid");return; }
522
+ try {
523
+ const result = await api({ operation: "preview_import", content: JSON.parse(await file.text()) });
524
+ const heading = node("h3");words(heading, "import_preview");preview.append(heading);
525
+ const note = node("p", undefined, "hint");words(note, "import_scope");preview.append(note);
526
+ for (const draft of result.drafts) {
527
+ const row = node("div", undefined, "connection-row"), info = node("div"), actions = node("div", undefined, "connection-actions");
528
+ info.append(node("h3", draft.config.name), node("p", draft.config.base_url, "hint"));
529
+ for (const warning of draft.warnings) { const text = node("p", undefined, "hint");words(text, "import_" + warning);info.append(text); }
530
+ actions.append(button("import_review", () => {
531
+ editApi();const config = draft.config;
532
+ apiForm.elements.name.value = config.name;apiForm.elements.base.value = config.base_url;apiForm.elements.auth_header.value = config.auth_header;
533
+ apiForm.elements.key_env.value = config.key_env || "";keyMode();
534
+ for (const input of apiForm.querySelectorAll('[name="protocol"]')) input.checked = Boolean(config.endpoints[input.value]);
535
+ setEndpoints(config.base_url, config.endpoints);models = structuredClone(config.models);selectedModels = new Set(models.map(model => model.id));modelRows();preview.hidden = true;
536
+ }));row.append(info, actions);preview.append(row);
537
+ }
538
+ preview.hidden = false;
539
+ } catch (error) { message(/^ccdx_import_/.test(error.message) ? error.message : "ccdx_import_format_invalid"); }
540
+ });
511
541
  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(); });
512
542
  el("refresh").addEventListener("click", () => { if (["#models", "#codex", "#claude"].includes(location.hash)) void load(); });
513
543
  window.addEventListener("hashchange", () => { apiForm.elements.key.value = "";mountClient();if (["#models", "#claude", "#codex"].includes(location.hash)) void load(); });
@@ -188,8 +188,9 @@
188
188
 
189
189
  <div data-view="models" hidden>
190
190
  <section class="panel dashboard-section" id="connection-sources">
191
- <div class="panel-heading"><h2 data-i18n="source_accounts">Accounts &amp; APIs</h2><button id="connection-add" type="button" data-i18n="api_add">Add API</button></div>
191
+ <div class="panel-heading"><h2 data-i18n="source_accounts">Accounts &amp; APIs</h2><div class="section-actions"><button id="connection-import" type="button" data-i18n="import_source">Import</button><input id="connection-import-file" type="file" accept=".json,application/json" hidden><button id="connection-add" type="button" data-i18n="api_add">Add API</button></div></div>
192
192
  <div id="model-providers" class="provider-tabs" role="tablist" aria-label="Model providers" data-i18n-label="model_providers"></div>
193
+ <section id="connection-import-preview" class="panel" hidden></section>
193
194
  <div id="connection-source-list"></div>
194
195
  <details id="connection-disabled-sources" class="connection-disabled" hidden><summary data-i18n="api_disabled_sources">Disabled sources</summary><div id="connection-disabled-source-list"></div></details>
195
196
  </section>
@@ -320,6 +321,7 @@
320
321
  <div class="section-actions usage-source-controls"><label><span data-i18n="source_entire_page">Source / entire page</span><select id="usage-provider"><option value="" data-i18n="all_providers">All providers</option></select></label>
321
322
  <label><span data-i18n="usage_model_page">Model / entire page</span><select id="analytics-model"><option value="" data-i18n="all_models">All models</option></select></label>
322
323
  <label><span data-i18n="usage_range_page">Time / entire page</span><select id="analytics-range"><option value="all" selected data-i18n="usage_all_history">All retained history</option><option value="7" data-i18n="7_days">Last 7 days</option><option value="30" data-i18n="30_days">Last 30 days</option><option value="90" data-i18n="90_days">Last 90 days</option><option value="365" data-i18n="usage_365_days">Last 365 days</option></select></label>
324
+ <label><span data-i18n="request_kind">Request purpose</span><select id="usage-purpose"><option value="" data-i18n="purpose_all">All purposes</option><option value="conversation" data-i18n="purpose_conversation">Conversation</option><option value="diagnostic" data-i18n="purpose_diagnostic">Diagnostic</option><option value="compatibility" data-i18n="purpose_compatibility">Compatibility test</option><option value="unknown" data-i18n="purpose_unknown">Unknown</option></select></label>
323
325
  <button id="refresh-usage" type="button" data-i18n="refresh_usage">Refresh usage</button></div>
324
326
 
325
327
  <details id="usage-analytics" class="panel dashboard-section analytics-section">
@@ -353,6 +353,30 @@
353
353
  "cap_apply_details": ["Apply to draft", "应用到草稿"],
354
354
  "cap_details_draft": ["Details updated. Save the source to apply.", "能力已加入草稿,请保存来源。"],
355
355
  "cap_preview_scope": ["Save to apply. Restart Claude after its settings change.", "保存后同步;Claude 配置更新后需重启。"],
356
+ "import_source": ["Import", "导入"],
357
+ "import_preview": ["Import preview", "导入预览"],
358
+ "import_review": ["Review draft", "检查草稿"],
359
+ "import_scope": ["API metadata only. Configure the key before saving; client access is granted separately.", "只导入 API 元数据。保存前配置密钥,应用权限另行设置。"],
360
+ "import_catalog_evidence_omitted": ["Cached capability evidence was omitted. Refresh this source after saving.", "未复制缓存能力证据。保存后刷新来源目录。"],
361
+ "import_auth_header_review": ["Review the Anthropic key header; simultaneous headers are not copied.", "请核对 Anthropic 密钥请求头,不复制双请求头策略。"],
362
+ "import_model_protocols_review": ["Review model interfaces after saving; foreign aliases are not copied.", "保存后核对模型接口,不复制外部路由别名。"],
363
+ "import_account_routing_omitted": ["Account rotation and routing rules were omitted.", "未导入账号轮换和路由规则。"],
364
+ "import_name_exists": ["This source name already exists. Review it or rename the draft.", "已有同名来源。请核对现有来源或修改草稿名称。"],
365
+ "import_endpoint_exists": ["This endpoint is already configured. Review before saving another source.", "已有相同接口地址。保存新来源前请核对。"],
366
+ "ccdx_import_format_invalid": ["Unsupported JSON format. Use CCDX API metadata, CC Switch Claude provider JSON or Magpie providers.json.", "JSON 格式不支持。请使用 CCDX API 元数据、CC Switch Claude 来源 JSON 或 Magpie providers.json。"],
367
+ "ccdx_import_size_invalid": ["Import at most 16 APIs in a file up to 256 KiB.", "文件最多 256 KiB,最多导入 16 个 API。"],
368
+ "ccdx_import_metadata_invalid": ["API metadata is invalid. Check HTTPS addresses, interface origins and model declarations.", "API 元数据无效。请核对 HTTPS 地址、接口来源和模型声明。"],
369
+ "ccdx_import_route_invalid": ["Replace external route aliases with actual source model IDs.", "请将外部路由别名改为实际来源模型 ID。"],
370
+ "source_cooling": ["Connection failures; this source interface will allow one recovery request shortly.", "连接连续失败,该来源接口将很快允许一次恢复请求。"],
371
+ "cap_field_max_tool_definitions": ["Maximum tool definitions", "工具定义上限"],
372
+ "cap_field_supported_parameters": ["Supported parameters", "支持的参数"],
373
+ "purpose_all": ["All purposes", "所有用途"],
374
+ "purpose_conversation": ["Conversation", "普通会话"],
375
+ "purpose_diagnostic": ["Diagnostic", "诊断"],
376
+ "purpose_compatibility": ["Compatibility test", "兼容测试"],
377
+ "purpose_unknown": ["Unknown", "未知"],
378
+ "cap_contract_checked": ["Installed Claude {version}: capability contract checked. Reopen Claude normally to load changed settings.", "已核对安装版 Claude {version} 的能力合约。正常重开 Claude 后加载变更。"],
379
+ "cap_effort_observed": ["A request sent reasoning level {effort} to its source.", "已观测到请求向来源发送推理档位 {effort}。"],
356
380
  "cap_sync_configured": ["Managed settings synchronized.", "受管设置已同步。"],
357
381
  "cap_sync_partially_preserved": ["Your existing settings were preserved.", "已保留现有手动设置。"],
358
382
  "cap_sync_limited": ["Some client settings cannot be expressed.", "部分能力无法在当前客户端配置中表达。"],
@@ -397,6 +397,7 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
397
397
  const { mode, provider, model, days, date } = JSON.parse(variant), query = new URLSearchParams();
398
398
  if (mode === "analytics") { query.set("analytics", "1");query.set("time_zone", Intl.DateTimeFormat().resolvedOptions().timeZone); }
399
399
  if (provider) query.set("provider", provider);
400
+ if (element("usage-purpose")?.value) query.set("purpose", element("usage-purpose").value);
400
401
  if (model) query.set("model", model);
401
402
  if (date?.startsWith("<")) query.set("to", new Date(Date.parse(date.slice(1)) - 86400000).toISOString().slice(0, 10));
402
403
  else if (date) { query.set("from", date);query.set("to", date); }
@@ -523,3 +524,5 @@ loadAnimation();
523
524
  refresh();
524
525
  loadAuth();
525
526
  animateLogo();
527
+
528
+ element("usage-purpose")?.addEventListener("change", () => { dashboardRefresh.invalidate("usage");dashboardRefresh.refresh("usage", { force: true }); });
@@ -385,7 +385,7 @@ export async function handleDashboardApi(req, res, pathname, {
385
385
  const provider = query.get("provider") || "";
386
386
  if (provider && !isProviderId(provider)) { sendJson(res, 400, { error: "Select a valid provider" });return; }
387
387
  let selection;
388
- try { selection = createUsageQuery({ provider, model: query.get("model") || "", days: query.get("days") || "all", from: query.get("from") || "", to: query.get("to") || "", timeZone: query.get("time_zone") || "UTC" }); }
388
+ try { selection = createUsageQuery({ provider, model: query.get("model") || "", purpose: query.get("purpose") || "", days: query.get("days") || "all", from: query.get("from") || "", to: query.get("to") || "", timeZone: query.get("time_zone") || "UTC" }); }
389
389
  catch (error) { sendJson(res, 400, { error: error.message });return; }
390
390
  let analytics = null;
391
391
  if (query.get("analytics") === "1") {
@@ -400,7 +400,7 @@ export async function handleDashboardApi(req, res, pathname, {
400
400
  }
401
401
  const abort = createRequestAbort(req, res);
402
402
  try {
403
- const filtered = selection.filters.model || selection.filters.from || selection.filters.to;
403
+ const filtered = selection.filters.purpose || selection.filters.model || selection.filters.from || selection.filters.to;
404
404
  const observedModels = new Set();
405
405
  const recordFilter = record => {
406
406
  if (observedModels.size < 100) observedModels.add(provider ? record.model || "unknown" : `${usageProvider(record)} / ${record.model || "unknown"}`);
@@ -50,7 +50,7 @@ function responseFailure(resp, text) {
50
50
  async function compatibilityRequest(fetchImpl, url, body, timeoutMs, headers) {
51
51
  const { resp, text } = await fetchTextWithTimeout(fetchImpl, url, {
52
52
  method: "POST",
53
- headers: { ...headers, "Content-Type": "application/json", Accept: body.stream ? "text/event-stream" : "application/json" },
53
+ headers: { ...headers, "X-CCDX-Purpose": "compatibility", "Content-Type": "application/json", Accept: body.stream ? "text/event-stream" : "application/json" },
54
54
  body: JSON.stringify(body),
55
55
  }, timeoutMs);
56
56
  if (!resp.ok) throw responseFailure(resp, text);
@@ -2,16 +2,17 @@ import { createHash } from "node:crypto";
2
2
 
3
3
  export const MODEL_PROTOCOLS = Object.freeze(["messages", "responses", "chat"]);
4
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"];
5
+ const limits = ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_budget_min", "reasoning_budget_max", "max_tool_definitions"];
6
+ export const MODEL_PARAMETERS = Object.freeze(["max_tokens", "max_output_tokens", "max_completion_tokens", "temperature", "top_p", "tools", "tool_choice", "parallel_tool_calls", "thinking", "output_config", "reasoning", "reasoning_effort", "response_format", "text", "stop", "stop_sequences", "stream", "stream_options"]);
6
7
  const flags = ["reasoning", "reasoning_required", "reasoning_adaptive", "tools", "parallel_tools", "streaming", "structured_output", "mid_conversation_system"];
7
- export const CAPABILITY_FIELDS = Object.freeze([...limits, ...flags, "reasoning_efforts", "reasoning_format", "thinking_modes", "input_modalities", "web_search"]);
8
+ export const CAPABILITY_FIELDS = Object.freeze([...limits, ...flags, "reasoning_efforts", "reasoning_format", "thinking_modes", "input_modalities", "web_search", "supported_parameters"]);
8
9
  const object = value => value && typeof value === "object" && !Array.isArray(value);
9
10
  export function validCapabilities(value) {
10
11
  return object(value) && Object.entries(value).every(([key, item]) => {
11
12
  if (limits.includes(key)) return Number.isSafeInteger(item) && item > 0 && item <= 100000000;
12
13
  if (flags.includes(key)) return typeof item === "boolean";
13
14
  if (key === "reasoning_format") return MODEL_PROTOCOLS.includes(item);
14
- const choices = key === "reasoning_efforts" ? REASONING_EFFORTS : key === "thinking_modes" ? ["disabled", "enabled", "adaptive", "between_tools"] : key === "input_modalities" ? ["text", "image", "audio", "video", "file"] : key === "web_search" ? MODEL_PROTOCOLS : null;
15
+ const choices = key === "supported_parameters" ? MODEL_PARAMETERS : key === "reasoning_efforts" ? REASONING_EFFORTS : key === "thinking_modes" ? ["disabled", "enabled", "adaptive", "between_tools"] : key === "input_modalities" ? ["text", "image", "audio", "video", "file"] : key === "web_search" ? MODEL_PROTOCOLS : null;
15
16
  return choices && Array.isArray(item) && item.length <= choices.length && new Set(item).size === item.length && item.every(v => choices.includes(v));
16
17
  }) && !(value.max_input_tokens && value.context_window && value.max_input_tokens > value.context_window)
17
18
  && !(value.reasoning_budget_min && value.reasoning_budget_max && value.reasoning_budget_min > value.reasoning_budget_max);
@@ -36,6 +37,7 @@ export function catalogCapabilities(model) {
36
37
  context_window: first(model.context_window, window.max_context_window_tokens),
37
38
  max_input_tokens: first(model.max_input_tokens, window.max_prompt_tokens, window.max_input_tokens),
38
39
  max_output_tokens: first(model.max_output_tokens, window.max_output_tokens),
40
+ max_tool_definitions: first(model.max_tool_definitions, window.max_tool_definitions),
39
41
  reasoning: first(typeof caps.reasoning === "boolean" ? caps.reasoning : undefined, supports.reasoning),
40
42
  reasoning_efforts: first(model.reasoning_efforts, supports.reasoning_effort),
41
43
  input_modalities: first(model.input_modalities, caps.input_modalities, supports.vision === true ? ["text", "image"] : undefined),
@@ -72,7 +74,8 @@ export function resolveModelCapabilities(model, { revision, checkedAt = null, bu
72
74
  export function claudeEffortsExpressible(values = {}) {
73
75
  const levels = values.reasoning === false ? [] : values.reasoning_efforts || [];
74
76
  const native = ["low", "medium", "high", "xhigh", "max"];
75
- 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));
77
+ const base = Math.min(2, Math.max(...levels.map(value => native.indexOf(value))));
78
+ return levels.length > 0 && levels.every(value => native.includes(value)) && native.slice(0, base + 1).every(value => levels.includes(value));
76
79
  }
77
80
 
78
81
  export function claudeEffortPrefix(values = {}) {
@@ -84,9 +87,19 @@ export function claudeEffortPrefix(values = {}) {
84
87
  return prefix.length === levels.length || prefix.length >= 2 ? prefix : [];
85
88
  }
86
89
 
90
+ function invalidRequestParameter(message, code, param) {
91
+ throw Object.assign(new Error(message), { code, statusCode: 400, param });
92
+ }
87
93
  export function constrainModelRequest(body, capability, protocol) {
88
94
  const values = capability?.values || {}, outputKey = protocol === "messages" ? "max_tokens" : protocol === "responses" ? "max_output_tokens" : "max_completion_tokens";
89
95
  let result = body;const applied = [];
96
+ if (body[outputKey] !== undefined && (!Number.isSafeInteger(body[outputKey]) || body[outputKey] <= 0)) invalidRequestParameter("The output token limit must be a positive integer.", "ccdx_api_output_limit_invalid", outputKey);
97
+ if (protocol === "chat" && body.max_tokens !== undefined && (!Number.isSafeInteger(body.max_tokens) || body.max_tokens <= 0)) invalidRequestParameter("The output token limit must be a positive integer.", "ccdx_api_output_limit_invalid", "max_tokens");
98
+ if (values.supported_parameters) for (const key of MODEL_PARAMETERS) {
99
+ if (Object.hasOwn(body, key) && !values.supported_parameters.includes(key)) invalidRequestParameter("This deployment does not declare support for the requested parameter: " + key + ".", "ccdx_api_parameter_unavailable", key);
100
+ }
101
+ if (values.max_tool_definitions && Array.isArray(body.tools) && body.tools.length > values.max_tool_definitions)
102
+ invalidRequestParameter("The number of tool definitions exceeds this deployment's declared limit of " + values.max_tool_definitions + ".", "ccdx_api_tool_limit_exceeded", "tools");
90
103
  if (values.max_output_tokens && Number.isFinite(body[outputKey]) && body[outputKey] > values.max_output_tokens) {
91
104
  result = { ...result, [outputKey]: values.max_output_tokens };applied.push("output_limit");
92
105
  }