codex-copilot-dx 1.3.26 → 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.
Files changed (42) hide show
  1. package/README.md +5 -2
  2. package/bin/cli.mjs +5 -2
  3. package/docs/ARCHITECTURE.md +16 -3
  4. package/docs/REFERENCE.md +28 -4
  5. package/package.json +1 -1
  6. package/src/adapter.mjs +4 -2
  7. package/src/claude-app-contract.mjs +96 -0
  8. package/src/claude-capability-config.mjs +26 -10
  9. package/src/claude-client-config.mjs +56 -7
  10. package/src/claude-gateway.mjs +7 -5
  11. package/src/claude-models.mjs +4 -2
  12. package/src/cli-command-spec.mjs +8 -2
  13. package/src/cli-management.mjs +26 -6
  14. package/src/client-versions.mjs +17 -13
  15. package/src/connection-client-sync.mjs +1 -0
  16. package/src/connection-management.mjs +5 -0
  17. package/src/connection-policy.mjs +2 -2
  18. package/src/connection-routing.mjs +2 -1
  19. package/src/connection-runtime.mjs +26 -2
  20. package/src/connection-view.mjs +11 -2
  21. package/src/dashboard/connections.js +33 -3
  22. package/src/dashboard/console.js +1 -1
  23. package/src/dashboard/context.js +8 -4
  24. package/src/dashboard/gemini.js +3 -7
  25. package/src/dashboard/index.html +5 -2
  26. package/src/dashboard/language.js +24 -0
  27. package/src/dashboard/status.js +8 -1
  28. package/src/dashboard/ui.js +3 -0
  29. package/src/dashboard-api.mjs +2 -2
  30. package/src/doctor-compat.mjs +1 -1
  31. package/src/model-capabilities.mjs +17 -4
  32. package/src/provider-cooldown.mjs +43 -0
  33. package/src/providers/api-model-metadata.mjs +7 -0
  34. package/src/providers/api.mjs +32 -11
  35. package/src/request-context.mjs +5 -0
  36. package/src/response-failures.mjs +4 -2
  37. package/src/safe-upstream-error.mjs +36 -4
  38. package/src/source-import.mjs +51 -0
  39. package/src/stream-performance.mjs +7 -5
  40. package/src/usage-analysis.mjs +2 -2
  41. package/src/usage-query.mjs +5 -2
  42. package/src/usage-store.mjs +2 -1
@@ -20,11 +20,9 @@
20
20
  if (!points.some(point => valid(point.input_tokens))) { label(host, "context_no_input");return; }
21
21
  if (!entry.identified) { label(host, "context_unassigned");return; }
22
22
  const width = host.clientWidth;if (!width) return;
23
- const height = 210, left = 64, right = 12, top = 25, bottom = 35;
23
+ const height = 210, right = 12, top = 25, bottom = 35;
24
24
  const measured = Math.max(...points.map(point => valid(point.input_tokens) ? point.input_tokens : 0), 1);
25
25
  const maximum = Math.max(measured, latest(entry).context_window_tokens || 0);
26
- const x = index => left + (width - left - right) * index / Math.max(1, points.length - 1);
27
- const y = value => top + (height - top - bottom) * (1 - value / maximum);
28
26
  const svg = document.createElementNS(ns, "svg");svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
29
27
  svg.setAttribute("role", "img");svg.setAttribute("aria-label", language.format("context_history"));host.append(svg);
30
28
  const shape = (tag, attributes, text) => {
@@ -32,10 +30,16 @@
32
30
  for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value);
33
31
  if (text !== undefined) node.textContent = text;svg.append(node);return node;
34
32
  };
33
+ const ticks = [0, maximum / 2, maximum].map(value => Math.round(value).toLocaleString());
34
+ const measures = ticks.map(text => shape("text", { visibility: "hidden" }, text));
35
+ const left = Math.max(64, Math.ceil(Math.max(...measures.map(node => node.getComputedTextLength()))) + 16);
36
+ measures.forEach(node => node.remove());
37
+ const x = index => left + (width - left - right) * index / Math.max(1, points.length - 1);
38
+ const y = value => top + (height - top - bottom) * (1 - value / maximum);
35
39
  for (let index = 0; index <= 2; index++) {
36
40
  const value = maximum * index / 2, py = y(value);
37
41
  shape("line", { x1: left, x2: width - right, y1: py, y2: py, class: "context-grid" });
38
- shape("text", { x: left - 8, y: py + 4, "text-anchor": "end" }, Math.round(value).toLocaleString());
42
+ shape("text", { x: left - 8, y: py + 4, "text-anchor": "end" }, ticks[index]);
39
43
  }
40
44
  shape("text", { x: left, y: 12 }, "tokens");
41
45
  let path = "", continuing = false;
@@ -35,17 +35,13 @@
35
35
  for(const model of groupedModels()){
36
36
  const chosen=new Set(draft||selected()),ids=model.efforts.map(item=>item.id);
37
37
  const row=document.createElement('tr'),name=document.createElement('td'),label=document.createElement('label'),input=document.createElement('input');
38
- input.type='checkbox';input.value=model.id;input.checked=ids.every(id=>chosen.has(id));input.indeterminate=!input.checked&&ids.some(id=>chosen.has(id));input.disabled=busy;input.setAttribute('aria-label',model.name);
38
+ input.type='checkbox';input.value=model.id;input.checked=ids.some(id=>chosen.has(id));input.disabled=busy;input.setAttribute('aria-label',model.name);
39
39
  const update=(values,checked)=>{const next=new Set(draft||selected());for(const id of values)if(checked)next.add(id);else next.delete(id);draft=[...next];notice=null;clear('gemini-note');render()};
40
- input.addEventListener('change',()=>update(ids,input.checked));
40
+ input.addEventListener('change',()=>{const saved=ids.filter(id=>selected().includes(id));update(input.checked&&saved.length?saved:ids,input.checked)});
41
41
  label.append(input,document.createTextNode(model.name));name.append(label);row.append(name);
42
42
  for(const [key,value]of [['source','GitHub Copilot'],['cap_context',count(model.context_window)]]){const cell=document.createElement('td');cell.textContent=value;cell.dataset.label=language.format(key);row.append(cell)}
43
43
  const efforts=document.createElement('td');efforts.dataset.label=language.format('cap_reasoning');
44
- for(const item of model.efforts){
45
- const label=document.createElement('label'),choice=document.createElement('input');choice.type='checkbox';choice.value=item.id;choice.checked=chosen.has(item.id);choice.disabled=busy;
46
- choice.setAttribute('aria-label',model.name+' · '+language.format(item.effort));choice.addEventListener('change',()=>update([item.id],choice.checked));
47
- label.append(choice,document.createTextNode(language.format(item.effort)));efforts.append(label,document.createTextNode(' '));
48
- }
44
+ efforts.textContent=model.efforts.map(item=>item.effort).join(' / ');
49
45
  row.append(efforts);list.append(row);
50
46
  }
51
47
  if(!state.models.length){const row=document.createElement('tr'),cell=document.createElement('td');cell.colSpan=4;language.set(cell,'gemini_no_models');row.append(cell);list.append(row)}
@@ -165,7 +165,7 @@
165
165
  <div data-view="gemini" hidden>
166
166
  <section class="connection-access"><div class="connection-row"><label for="gemini-enabled" data-i18n="gemini_access_title">Copilot access</label><label class="switch-hit"><input id="gemini-enabled" type="checkbox" role="switch" data-i18n-label="gemini_access_title" aria-label="Copilot access" disabled></label></div></section>
167
167
  <section class="panel dashboard-section">
168
- <div class="panel-heading"><h2 data-i18n="gemini_model_selection">Model selection</h2><span id="gemini-draft-state" role="status">—</span></div>
168
+ <div class="panel-heading"><h2 data-i18n="cap_visible_model">Available models</h2><span id="gemini-draft-state" role="status">—</span></div>
169
169
  <form id="gemini-model-form">
170
170
  <div class="table-wrap"><table class="binding-table"><thead><tr><th data-i18n="model">Model</th><th data-i18n="source">Source</th><th data-i18n="cap_context">Context</th><th data-i18n="cap_reasoning">Reasoning</th></tr></thead><tbody id="gemini-models"></tbody></table></div>
171
171
  <div class="section-actions"><button id="gemini-save" type="submit" data-i18n="api_save" disabled>Save</button><button id="gemini-cancel" type="button" data-i18n="cap_discard_changes" disabled>Discard changes</button></div>
@@ -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>
@@ -289,6 +290,7 @@
289
290
  <p class="hint" data-i18n="tools_local_scope">Local checks do not contact external services.</p>
290
291
  <p>Codex App: <strong id="client-version-codex">—</strong></p>
291
292
  <p>Claude App: <strong id="client-version-claude">—</strong></p>
293
+ <p>Antigravity: <strong id="client-version-antigravity">—</strong></p>
292
294
  <p class="hint" data-i18n="client_versions_scope">Installed versions only; running App adoption and compatibility are separate.</p>
293
295
  <div class="section-actions"><button id="check-local" type="button" data-i18n="tools_check_local">Check this computer</button></div>
294
296
  <p id="checks-note" class="table-note" role="status" aria-live="polite" data-i18n="tools_checks_empty">Run a check to see the results.</p>
@@ -319,6 +321,7 @@
319
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>
320
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>
321
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>
322
325
  <button id="refresh-usage" type="button" data-i18n="refresh_usage">Refresh usage</button></div>
323
326
 
324
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.", "部分能力无法在当前客户端配置中表达。"],
@@ -75,7 +75,14 @@
75
75
  }
76
76
  if (data.gemini || globalThis.ccdxGeminiStatus) {
77
77
  const gemini=data.gemini || globalThis.ccdxGeminiStatus;
78
- clients.append(tableRow(["Antigravity",gemini.enabled?"Google + Copilot":"Google",gemini.enabled?"configured":"access_paused",gemini.activity?.active>0?"active":gemini.route_observed?"observed":"unknown","—"],{labels:[2,3]}));
78
+ const setup=gemini.enabled&&gemini.source_enabled!==false?"configured":gemini.configured?"access_paused":"not_configured";
79
+ const service=gemini.configured===true?"running":gemini.configured===false?"unavailable":"unknown";
80
+ const row=tableRow(["Antigravity",gemini.enabled&&gemini.source_enabled!==false?"Google + GitHub Copilot":"Google",setup,service,"—"],{labels:[2,3]});
81
+ if(globalThis.ccdxIcons){
82
+ globalThis.ccdxIcons.set(row.children[2],setup,globalThis.ccdxIcons.kind(setup==="access_paused"?"paused":setup));
83
+ globalThis.ccdxIcons.set(row.children[3],service,globalThis.ccdxIcons.kind(service));
84
+ }
85
+ clients.append(row);
79
86
  }
80
87
  if (element("claude-client-state")) element("claude-client-state").hidden = Boolean(claudeClients?.children.length);
81
88
  text("source-summary", "count_providers", { count: providers.length });
@@ -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
  }
@@ -0,0 +1,43 @@
1
+ import { accessError } from "./access-settings.mjs";
2
+
3
+ const NETWORK_CODES = new Set(["ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"]);
4
+ export function confirmedNetworkFailure(error) {
5
+ for (let depth = 0; error && depth < 4; depth++, error = error.cause) if (NETWORK_CODES.has(error.code)) return true;
6
+ return false;
7
+ }
8
+
9
+ // One deployment/interface, two confirmed failures, one real recovery request.
10
+ // No paid probes, model switching or retry after output has started.
11
+ export function createProviderCooldown({ now = Date.now, delayMs = 5000 } = {}) {
12
+ let failures = 0, until = 0, recovering = false;
13
+ const snapshot = () => ({ state: until > now() ? "cooling" : recovering ? "recovering" : "ready", retry_after_ms: Math.max(0, until - now()), failures });
14
+ function enter() {
15
+ if (failures < 2) return false;
16
+ if (until > now() || recovering) {
17
+ const error = accessError("ccdx_api_cooling_down", 503);
18
+ error.message = error.jsonBody.error.message = "This source interface is temporarily cooling down after repeated connection failures. Retry shortly.";
19
+ error.retryAfterMs = Math.max(1000, until - now());throw error;
20
+ }
21
+ recovering = true;return true;
22
+ }
23
+ function complete(recovery, failed = false, cancelled = false, retryAfterMs = 0) {
24
+ if (recovery) recovering = false;
25
+ if (cancelled) return;
26
+ if (!failed) { if (failures) { failures = 0;until = 0; }return; }
27
+ failures = Math.min(2, failures + 1);
28
+ if (failures >= 2) until = now() + Math.min(30000, Math.max(delayMs, retryAfterMs));
29
+ }
30
+ return {
31
+ snapshot, enter, complete,
32
+ acquire() {
33
+ const recovery = enter();
34
+ let finished = false;
35
+ return {
36
+ finish({ failed = false, cancelled = false, retryAfterMs = 0 } = {}) {
37
+ if (finished) return;finished = true;
38
+ complete(recovery, failed, cancelled, retryAfterMs);
39
+ },
40
+ };
41
+ },
42
+ };
43
+ }
@@ -29,6 +29,13 @@ export function apiModelMetadata(model, { deployment, checked_at }) {
29
29
  delete values.max_input_tokens;
30
30
  }
31
31
  const protocols = Object.keys(messages).length ? { messages } : {};
32
+ // Parameter lists are protocol scoped. A generic OpenAI list says nothing
33
+ // about a gateway's Messages endpoint.
34
+ for (const protocol of ["messages", "responses", "chat"]) {
35
+ const parameters = caps.protocols?.[protocol]?.supported_parameters;
36
+ if (parameters !== undefined && validCapabilities({ supported_parameters: parameters }))
37
+ protocols[protocol] = { ...protocols[protocol], supported_parameters: parameters };
38
+ }
32
39
  const reported = Object.keys(values).length || Object.keys(protocols).length;
33
40
  const described = Object.keys(caps).length || ["max_tokens", "max_input_tokens", "max_output_tokens", "context_window", "reasoning_efforts"].some(key => Object.hasOwn(model, key));
34
41
  return { values, ...(Object.keys(protocols).length ? { protocols } : {}), deployment, checked_at,
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { createRoutePlan } from "../route-plan.mjs";
3
3
  import { accessError } from "../access-settings.mjs";
4
4
  import { publicModelCatalog } from "../provider-metadata.mjs";
5
- import { resolveClaudeModel } from "../claude-models.mjs";
5
+ import { claudeModelEntries } from "../claude-models.mjs";
6
6
  import { prepareResponsesPayload } from "../image-optimization.mjs";
7
7
  import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
8
8
  import { MAX_UPSTREAM_MODEL_CATALOG_BYTES, MAX_UPSTREAM_ERROR_BODY_BYTES, readBoundedResponseText } from "../http-transport.mjs";
@@ -20,6 +20,9 @@ import { apiModelDisplay } from "../api-model-display.mjs";
20
20
  import { adaptCallLessContext, CALL_LESS_TOOL_RETRIED, normalizeCallLessToolOutputs } from "../responses-tool-output.mjs";
21
21
  import { adaptMessagesToolSchemas, hasRootToolSchema, MESSAGES_TOOL_GUARD } from "../messages-tool-schema.mjs";
22
22
  import { loadRuntimeConfig } from "../runtime-config.mjs";
23
+ import { currentRequestContext } from "../request-context.mjs";
24
+ import { redactDiagnosticText } from "../diagnostic-text.mjs";
25
+ import { createProviderCooldown, confirmedNetworkFailure } from "../provider-cooldown.mjs";
23
26
 
24
27
  const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
25
28
  export function apiCatalog(config, env = process.env) {
@@ -29,7 +32,8 @@ export function apiCatalog(config, env = process.env) {
29
32
  supported_endpoints: model.protocols.map(api => paths[api]), model_picker_enabled: true, policy: { state: "enabled" },
30
33
  capability, protocol_capabilities }); });
31
34
  }
32
- export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork, modelDisplay = () => ({}) } = {}) {
35
+ export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork, modelDisplay = () => ({}), now = Date.now } = {}) {
36
+ const cooldowns = Object.fromEntries(["messages", "responses", "chat"].map(protocol => [protocol, createProviderCooldown({ now })]));
33
37
  const catalog = apiCatalog(config, env);
34
38
  const fingerprint = config.key_env ? createHash("sha256").update(env[config.key_env] || "").digest("hex") : "";
35
39
  const generation = parseInt(createHash("sha256").update(JSON.stringify(config) + fingerprint).digest("hex").slice(0, 8), 16);
@@ -55,8 +59,10 @@ export function createApiProvider({ config, secrets, env = process.env, platform
55
59
  return initialization.run("network", sharedSignal => networkFactory({ targets, env, platform, signal: AbortSignal.any([sharedSignal, lifetime.signal]) })
56
60
  .then(value => { if (closed || sharedSignal.aborted) { value.close();throw accessError("ccdx_api_closed", 503); }network = value;return value; }), { signal });
57
61
  };
62
+ let messageAliases;
58
63
  const selected = (id, api) => {
59
- const model = api === "messages" ? resolveClaudeModel(catalog, id) : catalog.find(model => model.id === id);
64
+ if (api === "messages" && !messageAliases) messageAliases = new Map(claudeModelEntries(catalog).map((entry, index) => [entry.name, catalog[index]]));
65
+ const model = api === "messages" && messageAliases.get(id) || catalog.find(model => model.id === id);
60
66
  if (!model?.supported_endpoints.includes(paths[api])) throw accessError("ccdx_api_model_unavailable");return model;
61
67
  };
62
68
  async function request(url, body, options = {}, api = "responses") {
@@ -64,7 +70,6 @@ export function createApiProvider({ config, secrets, env = process.env, platform
64
70
  if (config.key_env && !env[config.key_env]) throw accessError("ccdx_api_environment_key_missing", 503);
65
71
  const key = config.key_env ? checkedApiKey(env[config.key_env]) : await initialization.run("credential", () => secrets.get(config.secret_ref),
66
72
  { signal: options.signal ? AbortSignal.any([options.signal, lifetime.signal]) : lifetime.signal });
67
- const transport = await getNetwork(options.signal);
68
73
  const headers = { "Content-Type": "application/json", Accept: body?.stream ? "text/event-stream" : "application/json" };
69
74
  headers[api === "messages" && config.auth_header === "x-api-key" ? "x-api-key" : "Authorization"] = api === "messages" && config.auth_header === "x-api-key" ? key : `Bearer ${key}`;
70
75
  if (api === "messages") {
@@ -80,13 +85,21 @@ export function createApiProvider({ config, secrets, env = process.env, platform
80
85
  }
81
86
  const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
82
87
  if (serialized !== undefined) headers["Content-Length"] = String(Buffer.byteLength(serialized));
83
- options.onUpstreamStart?.();
84
- if (body && options.observeUpstream !== false) {
85
- markUpstreamStarted(body.stream === true);
86
- if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: api === "messages" ? body.max_tokens : api === "chat" ? body.max_completion_tokens : body.max_output_tokens });
87
- }
88
+ const cooldown = body && !options.countTokens ? cooldowns[api] : null;
89
+ const recovery = cooldown?.enter();let observed = false;
88
90
  try {
91
+ const transport = !closed && network && (network.healthy?.() ?? true) ? network : await getNetwork(options.signal);
92
+ options.onUpstreamStart?.();
93
+ if (body && options.observeUpstream !== false) {
94
+ markUpstreamStarted(body.stream === true);
95
+ if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: api === "messages" ? body.max_tokens : api === "chat" ? body.max_completion_tokens : body.max_output_tokens,
96
+ reasoning_effort_sent: api === "messages" ? body.output_config?.effort : api === "chat" ? body.reasoning_effort : body.reasoning?.effort });
97
+ }
89
98
  const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
99
+ const temporary = result.status === 502 || result.status === 503 || result.status === 504;
100
+ let retryAfterMs = 0;
101
+ if (temporary) { const retry = result.headers.get("retry-after");retryAfterMs = /^\d{1,8}$/.test(retry || "") ? Number(retry) * 1000 : Math.max(0, Date.parse(retry) - now()); }
102
+ cooldown?.complete(recovery, temporary, false, Number.isFinite(retryAfterMs) ? retryAfterMs : 0);observed = true;
90
103
  if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
91
104
  if (!result.ok) {
92
105
  const adapted = api === "responses" && [400, 422].includes(result.status) && !options.compatibilityRetried && !options.skipCallLessRetry
@@ -112,13 +125,20 @@ export function createApiProvider({ config, secrets, env = process.env, platform
112
125
  if (adapted || schemaCandidate) try { options.onUpstreamErrorHeaders?.(result.status); } catch { /* Preserve the original upstream failure. */ }
113
126
  const code = `ccdx_api_http_${result.status}`;
114
127
  const safeHeaders = { "Content-Type": "application/json" }, retry = result.headers.get("retry-after");
128
+ for (const name of ["x-request-id", "x-correlation-id", "request-id"]) {
129
+ const value = result.headers.get(name);
130
+ if (value && /^[a-z\d_.:-]{1,80}$/i.test(value) && redactDiagnosticText(value) === value) { safeHeaders["X-Request-Id"] = value;break; }
131
+ }
115
132
  if (/^\d{1,8}$/.test(retry || "")) safeHeaders["Retry-After"] = retry;
116
133
  else if (retry && Number.isFinite(Date.parse(retry))) safeHeaders["Retry-After"] = new Date(retry).toUTCString();
117
- return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message: reason?.message || code,
118
- ...(reason ? { upstream_code: reason.code } : {}) } }), { status: result.status, headers: safeHeaders });
134
+ const requestId=currentRequestContext()?.requestId;
135
+ const message=(reason?.message||"The source rejected the request (HTTP "+result.status+"); no recognised technical reason was returned.")+" Source: "+redactDiagnosticText(config.name||config.id)+". Model: "+redactDiagnosticText(body?.model||"unknown")+". API: "+api+"."+(requestId?" Request: "+requestId+".":"");
136
+ return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message,
137
+ ...(reason ? { upstream_code: reason.code, ...(reason.parameter ? { param: reason.parameter } : {}), ...(reason.maximum ? { maximum: reason.maximum } : {}) } : {}) } }), { status: result.status, headers: safeHeaders });
119
138
  }
120
139
  return result;
121
140
  } catch (error) {
141
+ if (!observed) cooldown?.complete(recovery, confirmedNetworkFailure(error), options.signal?.aborted === true);
122
142
  if (options.signal?.aborted) throw error;
123
143
  if (error.code === "ccdx_api_redirect_refused") throw error;
124
144
  const failure = accessError("ccdx_api_network_unavailable", 502);
@@ -152,6 +172,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
152
172
  models: family => catalog.filter(model => model.supported_endpoints.includes(family === "claude" ? paths.messages : paths.responses))
153
173
  .map(model => ({ ...model, ...modelDisplay(model.id), capability: model.protocol_capabilities[family === "claude" ? "messages" : "responses"] })),
154
174
  catalog: () => catalog,
175
+ health: () => Object.fromEntries(Object.entries(cooldowns).filter(([protocol]) => config.endpoints[protocol]).map(([protocol, cooldown]) => [protocol, cooldown.snapshot()])),
155
176
  publicCatalog(allowed = []) { return { source: "configured", checkedAt: config.checked_at || null, upstreamHost: new URL(config.base_url).hostname,
156
177
  advertised: catalog.length, models: publicModelCatalog(catalog.map(model => ({ ...model, ...modelDisplay(model.id) })), { maker: model => model.publisher || model.vendor || null,
157
178
  selectable: model => allowed.some(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)),
@@ -3,12 +3,17 @@ import { randomUUID } from "node:crypto";
3
3
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
4
4
 
5
5
  const requestContextStorage = new AsyncLocalStorage();
6
+ export const REQUEST_PURPOSES = Object.freeze(["conversation", "diagnostic", "compatibility", "unknown"]);
7
+ export function requestPurpose(value, fallback = "conversation") {
8
+ return REQUEST_PURPOSES.includes(value) ? value : fallback;
9
+ }
6
10
 
7
11
  export function createRequestId() {
8
12
  return randomUUID();
9
13
  }
10
14
 
11
15
  export function runWithRequestContext(context, callback) {
16
+ context.purpose = requestPurpose(context.purpose);
12
17
  return requestContextStorage.run(context, callback);
13
18
  }
14
19
 
@@ -114,19 +114,21 @@ export function upstreamErrorEvidence(text, { includeMessage = false, status = n
114
114
  const technical = value => typeof value === "string" && /^[a-z\d_.:-]{1,80}$/i.test(value)
115
115
  && redactDiagnosticText(value) === value ? value : undefined;
116
116
  const param = typeof error.param === "string" && error.param.length <= 160
117
- && /^(?:model|input|tools|tool_choice|reasoning|text|temperature|top_p|max_output_tokens|service_tier|store|stream|include|previous_response_id|parallel_tool_calls)(?:\.[a-z_][a-z\d_]*|\[\d+\])*$/i.test(error.param)
117
+ && /^(?:model|messages|input|tools|tool_choice|reasoning|output_config|thinking|text|temperature|top_p|max_tokens|max_output_tokens|max_completion_tokens|service_tier|store|stream|include|previous_response_id|parallel_tool_calls)(?:\.[a-z_][a-z\d_]*|\[\d+\])*$/i.test(error.param)
118
118
  ? error.param : undefined;
119
119
  const upstreamCode = (safeUpstreamReason(error.upstream_code, status) || safeUpstreamReason(error.code, status)
120
120
  || safeUpstreamReason(error.type, status))?.code;
121
121
  return { error_body: "structured", code: technical(error.code), error_type: technical(error.type),
122
122
  ...(upstreamCode ? { upstream_code: upstreamCode } : {}),
123
+ ...(upstreamCode && Number.isSafeInteger(error.maximum) && error.maximum > 0 && error.maximum <= 100000000 ? { reported_maximum: error.maximum } : {}),
123
124
  parameter: param, ...(includeMessage && typeof error.message === "string" ? { diagnostic_message: safeFailureMessage(error.message) } : {}) };
124
125
  }
125
126
 
126
127
  export function requestOptionsEvidence(body) {
127
128
  const result = {};
128
129
  if (!body || typeof body !== "object") return result;
129
- if (["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"].includes(body.reasoning?.effort)) result.reasoning_effort = body.reasoning.effort;
130
+ const effort = body.reasoning?.effort ?? body.output_config?.effort ?? body.reasoning_effort;
131
+ if (["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"].includes(effort)) result.reasoning_effort = effort;
130
132
  if (["auto", "default", "flex", "priority", "scale"].includes(body.service_tier)) result.service_tier = body.service_tier;
131
133
  if (["text", "json_object", "json_schema"].includes(body.text?.format?.type)) result.output_format = body.text.format.type;
132
134
  if (Number.isSafeInteger(body.max_output_tokens) && body.max_output_tokens >= 0) result.max_output_tokens = body.max_output_tokens;
@@ -1,5 +1,6 @@
1
1
  import { isMissingCallIdError } from "./responses-tool-output.mjs";
2
2
  import { isRootToolSchemaError } from "./messages-tool-schema.mjs";
3
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
3
4
 
4
5
  // Only fixed, documented-shaped codes leave this module; vendor messages and
5
6
  // request data are never returned or logged.
@@ -12,6 +13,13 @@ const reasons = new Map([
12
13
  ["context_length_exceeded", { statuses: [400, 413, 422], message: "The source reports that the context is too long." }],
13
14
  ["context_window_exceeded", { statuses: [400, 413, 422], message: "The source reports that the context is too long." }],
14
15
  ["content_policy_violation", { statuses: [400, 403, 422], message: "The source rejected the request under its content policy." }],
16
+ ["invalid_request_error", { statuses: [400, 422], message: "The source rejected the request parameters." }],
17
+ ["unsupported_parameter", { statuses: [400, 422], message: "The source does not support a requested parameter." }],
18
+ ["output_limit_invalid", { statuses: [400, 422], message: "The source rejected the output token limit." }],
19
+ ["tool_limit_exceeded", { statuses: [400, 422], message: "The source rejected the number of tool definitions." }],
20
+ ["reasoning_parameter_unsupported", { statuses: [400, 422], message: "The source does not support the requested reasoning parameter." }],
21
+ ["authentication_error", { statuses: [401], message: "The source rejected authentication." }],
22
+ ["permission_denied", { statuses: [403], message: "The source denied access to this model or operation." }],
15
23
  ]);
16
24
  const MAX_ACTIVE_READS = 4;
17
25
  let activeReads = 0;
@@ -25,6 +33,32 @@ export function safeUpstreamReason(code, status) {
25
33
  return reason?.statuses.includes(status) ? { code, message: reason.message } : null;
26
34
  }
27
35
 
36
+ export function safeUpstreamParameter(value){
37
+ return typeof value==="string"&&value.length<=160&&/^(?:model|messages|input|tools|tool_choice|reasoning|output_config|thinking|temperature|top_p|max_tokens|max_output_tokens|max_completion_tokens|response_format|text|stream|stream_options|stop|stop_sequences)(?:\.[a-z_][a-z\d_]*|\[\d+\])*$/i.test(value)&&redactDiagnosticText(value)===value?value:undefined;
38
+ }
39
+
40
+ export function classifyUpstreamError(value,status){
41
+ const error=value?.error??value,text=typeof error==="string"?error:typeof error?.message==="string"?error.message:"";
42
+ if(text.length>65536)return null;
43
+ const param=safeUpstreamParameter(error?.param||error?.parameter);
44
+ let code;
45
+ if([400,413,422].includes(status)&&/(context (?:length|window)|input tokens|上下文).{0,80}(?:exceed|too (?:long|large)|超|超过)|(?:exceed|超).{0,60}(?:context|上下文)/i.test(text))code="context_length_exceeded";
46
+ else if([400,422].includes(status)&&/max_(?:completion_)?tokens|max_output_tokens|output token limit|输出.{0,12}(?:上限|限制)/i.test(text)&&/(?:maximum|at most|less than|exceed|between|invalid|unsupported|最多|超过|不支持)/i.test(text))code="output_limit_invalid";
47
+ else if([400,422].includes(status)&&/(?:too many|maximum number of|at most).{0,40}tools|工具.{0,20}(?:过多|超过)/i.test(text))code="tool_limit_exceeded";
48
+ else if([400,422].includes(status)&&/(?:effort|thinking|reasoning).{0,60}(?:not support|unsupported)|not support.{0,60}(?:effort|thinking|reasoning)/i.test(text))code="reasoning_parameter_unsupported";
49
+ const selected=safeUpstreamReason(code,status)||safeUpstreamReason(error?.code,status)||safeUpstreamReason(error?.type,status);
50
+ if(!selected)return null;
51
+ const inferred = code === "output_limit_invalid" ? /\b(max_(?:completion_)?tokens|max_output_tokens)\b/i.exec(text)?.[1]?.toLowerCase() : code === "tool_limit_exceeded" ? "tools" : undefined;
52
+ const bounds = {};
53
+ if (["output_limit_invalid", "tool_limit_exceeded", "context_length_exceeded"].includes(selected.code)) {
54
+ const maximum = /(?:maximum(?: (?:context length|number of tools|tokens))?(?: is| of)?|at most|must be (?:less than or equal to|<=)|最多|上限(?:为)?)\s*[:=]?\s*(\d[\d,]{0,11})(?![\d,])/i.exec(text)?.[1];
55
+ const n = maximum && Number(maximum.replaceAll(",", ""));
56
+ if (Number.isSafeInteger(n) && n > 0 && n <= 100000000) bounds.maximum = n;
57
+ }
58
+ return { ...selected, ...(param || inferred ? { parameter: param || inferred } : {}), ...bounds,
59
+ message: selected.message + (param ? " Parameter: " + param + "." : "") + (bounds.maximum ? " Reported maximum: " + bounds.maximum + "." : "") };
60
+ }
61
+
28
62
  function readChunk(reader, signal) {
29
63
  if (signal.aborted) return Promise.reject(signal.reason);
30
64
  return new Promise((resolve, reject) => {
@@ -67,10 +101,8 @@ export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200
67
101
  const text = Buffer.concat(chunks, bytes).toString("utf8");
68
102
  if (missingCallId && isMissingCallIdError(response.status, text)) return { code: "ccdx_missing_call_id", message: "The source requires a tool call ID." };
69
103
  if (rootToolSchema && isRootToolSchemaError(response.status, text)) return { code: "ccdx_tool_schema_root_unsupported", message: "The source rejected a tool's root schema." };
70
- let value;try { value = JSON.parse(text); } catch { return null; }
71
- const error = value?.error;
72
- if (!error || typeof error !== "object" || Array.isArray(error)) return null;
73
- return safeUpstreamReason(error.code, response.status) || safeUpstreamReason(error.type, response.status);
104
+ let value;try { value = JSON.parse(text); } catch { value=text; }
105
+ return classifyUpstreamError(value,response.status);
74
106
  } catch (error) {
75
107
  if (signal?.aborted) signal.throwIfAborted();
76
108
  return null;
@@ -0,0 +1,51 @@
1
+ import { checkedApi, CLIENT_IDS } from "./access-settings.mjs";
2
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
3
+
4
+ const object = value => value && typeof value === "object" && !Array.isArray(value);
5
+ const metadata = config => Object.fromEntries(["name", "base_url", "endpoints", "auth_header", "models", "key_env"].filter(key => config[key] !== undefined).map(key => [key, config[key]]));
6
+ const routes = { messages: "messages", responses: "responses", chat: "chat/completions" };
7
+ const append = (base, route) => base.replace(/\/+$/, "") + "/" + route;
8
+
9
+ // Only an explicitly supplied JSON file is interpreted. Credential values,
10
+ // tool permissions, commands, cached evidence and foreign route IDs stay out.
11
+ export function previewSourceImport(value, existing = []) {
12
+ if (!object(value) && !Array.isArray(value)) throw new Error("ccdx_import_format_invalid");
13
+ let format, entries;
14
+ if (object(value.config) && value.config.base_url) { format = "ccdx";entries = [value.config]; }
15
+ else if (Array.isArray(value.apis)) { format = "ccdx";entries = value.apis; }
16
+ else if (object(value.settingsConfig)) { format = "cc-switch";entries = [value]; }
17
+ else if (Array.isArray(value.providers) && value.providers.some(row => row?.anthropic || row?.responses || row?.chat)) { format = "magpie";entries = value.providers; }
18
+ else if (object(value.providers) && Object.values(value.providers).every(row => object(row?.settingsConfig))) { format = "cc-switch";entries = Object.values(value.providers); }
19
+ else throw new Error("ccdx_import_format_invalid");
20
+ if (!entries.length || entries.length > 16) throw new Error("ccdx_import_size_invalid");
21
+ const drafts = entries.map((entry, index) => {
22
+ const warnings = [];let config;
23
+ if (!object(entry)) throw new Error("ccdx_import_format_invalid");
24
+ if (format === "ccdx") {
25
+ config = metadata(entry);
26
+ config.models = (config.models || []).map(model => Object.fromEntries(["id", "protocols", "context_window", "reasoning_efforts", "capabilities"].filter(key => model[key] !== undefined).map(key => [key, model[key]])));
27
+ if (entry.models?.some(model => model.metadata)) warnings.push("catalog_evidence_omitted");
28
+ } else if (format === "cc-switch") {
29
+ const env = entry.settingsConfig.env;
30
+ if (!object(env) || typeof env.ANTHROPIC_BASE_URL !== "string") throw new Error("ccdx_import_format_invalid");
31
+ const base = env.ANTHROPIC_BASE_URL;
32
+ config = { name: entry.name, base_url: base, endpoints: { messages: append(base, "v1/messages") }, auth_header: entry.meta?.apiKeyField === "ANTHROPIC_API_KEY" ? "x-api-key" : "bearer", models: [] };
33
+ warnings.push("model_protocols_review");
34
+ } else {
35
+ const endpoints = Object.fromEntries(Object.entries({ messages: entry.anthropic, responses: entry.responses, chat: entry.chat }).filter(([, base]) => base).map(([protocol, base]) => [protocol, append(base, protocol === "messages" ? "v1/messages" : routes[protocol])]));
36
+ config = { name: entry.name, base_url: Object.values({ responses: entry.responses, chat: entry.chat, messages: entry.anthropic }).find(Boolean), endpoints, auth_header: entry.authHeader === "x-api-key" ? "x-api-key" : "bearer", models: [] };
37
+ if (entry.anthropic && !["x-api-key", "bearer"].includes(entry.authHeader)) warnings.push("auth_header_review");
38
+ if (entry.models?.length) warnings.push("model_protocols_review");
39
+ if (entry.keys?.length || entry.keyProtocol || entry.groups || entry.routing) warnings.push("account_routing_omitted");
40
+ }
41
+ const allowed = format === "ccdx" && Array.isArray(value.allowed) ? value.allowed.filter(id => CLIENT_IDS.includes(id)) : [];
42
+ checkedApi({ ...config, id: "api_import", enabled: true, ...(config.key_env ? {} : { secret_ref: "0".repeat(32) }) });
43
+ if (redactDiagnosticText(config.name) !== config.name || redactDiagnosticText(config.base_url) !== config.base_url) throw new Error("ccdx_import_metadata_invalid");
44
+ if (Object.values(config.endpoints).some(url => redactDiagnosticText(url) !== url) || config.models.some(model => redactDiagnosticText(model.id) !== model.id)) throw new Error("ccdx_import_metadata_invalid");
45
+ if (config.models.some(model => /^(?:ccdx\/|mythos-ccdx-)/.test(model.id))) throw new Error("ccdx_import_route_invalid");
46
+ if (existing.some(source => source.name?.trim().toLowerCase() === config.name.trim().toLowerCase())) warnings.push("name_exists");
47
+ if (existing.some(source => source.base_url === config.base_url)) warnings.push("endpoint_exists");
48
+ return { number: index + 1, config, requested_access: allowed, allowed: [], warnings, credential: config.key_env ? "environment" : "private_input_required" };
49
+ });
50
+ return { format, saved: false, drafts };
51
+ }