codex-copilot-dx 1.2.23 → 1.2.25

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.
@@ -433,6 +433,8 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
433
433
 
434
434
  .flow-network { position:relative;display:grid;grid-template-columns:minmax(130px,1fr) 70px minmax(170px,1fr);column-gap:clamp(36px,6vw,92px);align-items:stretch;min-height:236px;margin:26px 0 18px; }
435
435
  .flow-wires { position:absolute;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible; }
436
+ .flow-activity { will-change:transform; }
437
+ .flow-wires .flow-split { visibility:hidden;animation:none; }
436
438
  .flow-column,.flow-hub-column { position:relative;min-width:0; }
437
439
  .flow-column { display:flex;flex-direction:column; }
438
440
  .flow-column-title { height:18px;line-height:18px;margin:0 0 18px;color:var(--muted);font-size:11px;text-align:center; }
@@ -461,14 +463,14 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
461
463
  .flow-caption { display:flex;align-items:center;flex-wrap:wrap;gap:10px 16px;min-height:30px;font-size:11px;color:var(--muted); }
462
464
  .flow-caption button { padding:5px 9px; }
463
465
  .flow-wire { fill:none;stroke:var(--border);stroke-width:1;stroke-linecap:round;stroke-linejoin:round; }
464
- .flow-live { stroke:var(--accent);opacity:.55; }
466
+ .flow-live { stroke:var(--accent);opacity:.68; }
465
467
  .flow-dim { opacity:.35; }
466
- .flow-packet,.flow-wait { fill:var(--accent); }
467
- .flow-packet { offset-distance:100%;animation:flow-travel 2.4s linear infinite; }
468
- #request-flow[data-paused="true"] .flow-packet,#request-flow[data-paused="true"] #flow-state::before { animation-play-state:paused; }
468
+ .flow-streaming { stroke-dasharray:4 8;animation:flow-dash 1.5s linear infinite; }
469
+ .flow-waiting { stroke-dasharray:4 8; }
470
+ #request-flow[data-paused="true"] .flow-streaming,#request-flow[data-paused="true"] #flow-state::before { animation-play-state:paused; }
469
471
  #request-flow[data-state="idle"] #flow-state { display:inline-flex;align-items:center;gap:9px; }
470
472
  #request-flow[data-state="idle"] #flow-state::before { content:"";width:4px;height:4px;border-radius:50%;background:var(--accent);box-shadow:0 0 10px 3px color-mix(in srgb,var(--accent) 25%,transparent);animation:flow-breathe 3.2s ease-in-out infinite; }
471
- @keyframes flow-travel { from { offset-distance:100%; } to { offset-distance:0%; } }
473
+ @keyframes flow-dash { from { stroke-dashoffset:0; } to { stroke-dashoffset:24; } }
472
474
  @keyframes flow-breathe { 0%,100% { opacity:.45; } 50% { opacity:1; } }
473
475
  @media(max-width:760px) {
474
476
  .flow-network { grid-template-columns:minmax(105px,1fr) 66px minmax(120px,1fr);column-gap:18px; }
@@ -484,7 +486,7 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
484
486
  .flow-logo { width:26px;height:26px; }
485
487
  #flow-hub,.flow-halo { width:48px;height:48px; }
486
488
  }
487
- @media(prefers-reduced-motion:reduce) { .flow-packet,.flow-halo-turn,#request-flow[data-state="idle"] #flow-state::before { animation:none;transition:none; } }
489
+ @media(prefers-reduced-motion:reduce) { .flow-streaming,.flow-halo-turn,#request-flow[data-state="idle"] #flow-state::before { animation:none;transition:none; } }
488
490
 
489
491
  /* Model capability and application binding controls share the existing palette. */
490
492
  .client-segments { margin-bottom: 18px; }
@@ -528,3 +530,26 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
528
530
  @media(max-width:640px) { .nightly-rules { grid-template-columns:1fr; } }
529
531
 
530
532
  .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
533
+
534
+ #flow-models { align-items:stretch; }
535
+ #flow-models .flow-node { width:100%; }
536
+ #flow-models .flow-choice { text-align:left; }
537
+ .flow-column:last-child .flow-column-title { text-align:left;padding-left:9px; }
538
+ .model-maker { display:block;margin-top:5px;color:var(--muted);font-size:11px;font-weight:400; }
539
+ .model-identity { display:grid;grid-template-columns:auto 1fr;gap:8px 16px;font-size:12px;margin:18px 0; }
540
+ .model-identity dt { color:var(--muted); }
541
+ .model-identity dd { margin:0;overflow-wrap:anywhere; }
542
+ .memory-model-row { display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;padding:18px 0; }
543
+ .memory-model-value { display:flex;align-items:center;gap:12px;flex-wrap:wrap; }
544
+ .memory-model-notice { margin:0 0 18px;color:var(--incomplete);font-size:12px;line-height:1.7; }
545
+ .memory-model-badge { display:block;margin:5px 0 0 23px;color:var(--muted);font-size:11px; }
546
+ .memory-confirm { width:min(430px,calc(100% - 32px));border:1px solid var(--button-border);border-radius:2px;background:var(--surface);color:var(--text);padding:24px;font:inherit; }
547
+ .memory-confirm::backdrop { background:color-mix(in srgb,var(--page) 70%,transparent);backdrop-filter:blur(2px); }
548
+ .memory-confirm h2 { margin:0;color:var(--strong);font-size:18px; }
549
+ .memory-confirm p { line-height:1.8; }
550
+ .memory-confirm .section-actions { justify-content:flex-end; }
551
+ @media(max-width:460px) { .flow-column:last-child .flow-column-title { padding-left:4px; } }
552
+
553
+ .memory-model-value .hint { margin:0; }
554
+ .memory-model-value { min-width:0;max-width:100%; }
555
+ .memory-model-value strong { min-width:0;overflow-wrap:anywhere; }
@@ -186,12 +186,14 @@ function applyModels(data, { changed }) {
186
186
  for (const model of data.models) {
187
187
  const clients = (model.clients || []).map(id => ({ codex: "Codex App", claude_app: "Claude App", claude_code: "Claude Code" })[id] || id).join(" / ") || "—";
188
188
  const row = tableRow([model.id, clients, ""]);row.children[0].className = "model-name";
189
+ if (model.vendor && model.vendor !== "Unknown") { const maker = document.createElement("span");maker.className = "model-maker";maker.textContent = model.vendor;row.children[0].append(maker); }
189
190
  const details = document.createElement("details"), summary = document.createElement("summary"), fields = document.createElement("dl");
190
191
  details.dataset.model = model.id;details.open = expanded.has(model.id);fields.className = "failure-detail";
191
192
  localize(summary, "model_details");details.append(summary, fields);
192
- for (const [key, value, translated] of [["vendor", model.vendor || "—"], ["api", model.endpoints.join(" / ") || "—"],
193
+ for (const [key, value, translated] of [["vendor", model.vendor && model.vendor !== "Unknown" ? model.vendor : phrase("cap_unknown")], ["model_owner", model.owned_by], ["api", model.endpoints.join(" / ") || "—"],
193
194
  ["reasoning", model.reasoning_efforts?.join(" / ") || "—"], ["state", model.preview ? "preview" : model.state || "listed", true],
194
195
  ["model_window", number(model.context_window)]]) {
196
+ if (value === undefined) continue;
195
197
  const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);
196
198
  if (translated) localize(detail, value);else detail.textContent = value;
197
199
  fields.append(term, detail);
@@ -315,7 +317,8 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
315
317
  ["network_failure_stage", network ? phrase(`network_stage_${network.stage}`) : null],
316
318
  ["network_cause_code", network?.cause_code], ["http_status", catalog?.http_status || diagnostic.http_status], ["last_success", catalog?.last_success_at], ["upstream_request_id", catalog?.request_id]]) {
317
319
  if (value === null || value === undefined || value === "") continue;
318
- const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);
320
+ if (value === undefined) continue;
321
+ const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);
319
322
  if (value?.key) localize(detail, value.key, value.values);else detail.textContent = String(value).slice(0, 300);
320
323
  fields.append(term, detail);
321
324
  }
@@ -322,7 +322,7 @@ export function isAbortLikeError(err) {
322
322
 
323
323
  export function abortErrorStatusCode(reason) {
324
324
  if (reason === "request_body_timeout") return 408;
325
- if (["responses_prepare_timeout", "upstream_timeout", "stream_handshake_timeout", "stream_idle_timeout"].includes(reason)) return 504;
325
+ if (["responses_prepare_timeout", "messages_prepare_timeout", "upstream_timeout", "stream_handshake_timeout", "stream_idle_timeout"].includes(reason)) return 504;
326
326
  if (reason === "client_aborted" || reason === "client_closed") return 499;
327
327
  return 502;
328
328
  }
@@ -8,9 +8,9 @@ export function modelReasoningEfforts(model) {
8
8
  return Array.isArray(values) ? [...new Set(values.filter(value => typeof value === "string" && /^[a-z][a-z0-9_-]{0,15}$/.test(value)))].slice(0, 16) : null;
9
9
  }
10
10
 
11
- export function publicModelCatalog(models, { clients = () => [], selectable = () => false } = {}) {
11
+ export function publicModelCatalog(models, { clients = () => [], selectable = () => false, maker = model => model.publisher || model.vendor || model.owned_by || "Unknown" } = {}) {
12
12
  return models.slice(0, 1000).filter(model => typeof model?.id === "string").map(model => ({
13
- id: model.id, vendor: model.publisher || model.vendor || model.owned_by || "Unknown",
13
+ id: model.id, vendor: maker(model), ...(model.owned_by ? { owned_by: model.owned_by } : {}),
14
14
  endpoints: [["responses", ["/responses", "/v1/responses"]], ["chat", ["/chat/completions", "/v1/chat/completions"]],
15
15
  ["messages", ["/v1/messages"]]].filter(([, paths]) => paths.some(path => model.supported_endpoints?.includes(path))).map(([label]) => label),
16
16
  preview: model.preview === true, selectable: selectable(model), clients: clients(model),
@@ -2,60 +2,65 @@ import { createHash } from "node:crypto";
2
2
  import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
3
3
  import { readBoundedResponseText } from "../http-transport.mjs";
4
4
 
5
- // Owned by one immutable API/key configuration. No conversation or credential
6
- // is cached; only small response envelopes and bounded in-flight hashes exist.
5
+ // One API/key configuration owns these bounded observations and operations.
6
+ // Unknown capabilities share their first real count, not another inference.
7
7
  export function createApiTokenCounter({ request, now = Date.now }) {
8
- const flights = new Map(), unavailable = new Map(), shared = createAbortAwareSingleflight();
9
- let bytes = 0;
10
- const missed = () => new Response(JSON.stringify({ type: "error", error: { type: "api_error",
11
- code: "ccdx_api_count_tokens_unavailable", message: "This source's token-count endpoint returned HTTP 404. Message generation is separate." } }),
12
- { status: 404, headers: { "Content-Type": "application/json" } });
8
+ const flights = new Map(), capabilities = new Map(), shared = createAbortAwareSingleflight();let bytes = 0;
9
+ const missed = () => new Response(JSON.stringify({ type: "error", error: { type: "api_error", code: "ccdx_api_count_tokens_unavailable",
10
+ message: "This source's token-count endpoint returned HTTP 404. Message generation is separate." } }), { status: 404, headers: { "Content-Type": "application/json" } });
11
+ const observe = (scope, status) => { capabilities.delete(scope);capabilities.set(scope, { status, at: now() });while (capabilities.size > 128) capabilities.delete(capabilities.keys().next().value); };
13
12
  return {
14
13
  async count(body, options = {}) {
15
14
  if (options.signal?.aborted) throw options.signal.reason;
16
15
  const headers = Object.fromEntries(["anthropic-version", "anthropic-beta"].map(name => [name, options.headers?.[name] || ""]));
17
- const scope = createHash("sha256").update(JSON.stringify([body.model, headers])).digest("hex");
18
- const at = now(), seen = unavailable.get(scope);
19
- if (seen !== undefined && at >= seen && at - seen < 60000) { options.onCountObservation?.({ cached: true });return missed(); }
20
- unavailable.delete(scope);
21
- const serialized = JSON.stringify(body), size = Buffer.byteLength(serialized);
22
- const key = size <= 1024 * 1024 ? createHash("sha256").update(scope).update(serialized).digest("hex") : null;
23
- const waiter = { start: options.onUpstreamStart, observe: options.onCountObservation, signal: options.signal };
24
- let flight = flights.get(key);
25
- if (flight && [...flight.waiters].every(item => item.signal?.aborted)) {
26
- flights.delete(key);bytes -= size;flight = null;
27
- }
28
- const joinable = Boolean(flight) || size <= 1024 * 1024 && flights.size < 16 && bytes + size <= 4 * 1024 * 1024;
29
- if (!flight) {
30
- flight = { key: {}, waiters: new Set(), started: false, shared: false };
31
- if (joinable) { flights.set(key, flight);bytes += size; }
32
- } else flight.shared = true;
33
- flight.waiters.add(waiter);
34
- const start = item => { item.start?.();item.observe?.({ upstream: true, shared: flight.shared }); };
35
- if (flight.started) start(waiter);
36
- const run = async signal => {
16
+ const scope = createHash("sha256").update(JSON.stringify([body.model, headers])).digest("hex"), known = capabilities.get(scope), at = now();
17
+ if (known?.status === 404 && at >= known.at && at - known.at < 60000) { options.onCountObservation?.({ cached: true });return missed(); }
18
+ if (known?.status === 404) capabilities.delete(scope);
19
+ const serialized = JSON.stringify(body), size = Buffer.byteLength(serialized), hash = size <= 1024 * 1024 ? createHash("sha256").update(scope).update(serialized).digest("hex") : null;
20
+ const identity = hash || {};
21
+ async function run(probe) {
22
+ const key = probe ? "probe:" + scope : "body:" + hash, waiter = { start: options.onUpstreamStart, observe: options.onCountObservation, signal: options.signal, identity };
23
+ let flight = flights.get(key);
24
+ if (flight && [...flight.waiters].every(item => item.signal?.aborted)) { flights.delete(key);bytes -= flight.bytes;flight = null; }
25
+ const joinable = (probe || hash !== null) && (Boolean(flight) || flights.size < 16 && (probe || bytes + size <= 4 * 1024 * 1024));
26
+ if (!flight || !joinable) {
27
+ flight = { key: {}, identity, bytes: probe ? 0 : size, waiters: new Set(), started: false, shared: false };
28
+ if (joinable) { flights.set(key, flight);bytes += flight.bytes; }
29
+ } else if (flight.identity === identity) flight.shared = true;
30
+ flight.waiters.add(waiter);
31
+ const start = item => {
32
+ item.start?.();
33
+ item.observe?.(item.identity === flight.identity ? { upstream: true, shared: flight.shared } : { waited: true });
34
+ };
35
+ if (flight.started) start(waiter);
36
+ const task = async signal => {
37
+ try {
38
+ if (signal?.aborted) throw signal.reason;
39
+ const response = await request(body, { ...options, bodyText: serialized, signal, observeUpstream: false,
40
+ onUpstreamStart() { flight.started = true;for (const item of flight.waiters) if (!item.signal?.aborted) start(item); } });
41
+ if (signal?.aborted) { await response.body?.cancel();throw signal.reason; }
42
+ if (response.status === 404) {
43
+ await response.body?.cancel();observe(scope, 404);const result = missed();
44
+ return { identity: flight.identity, status: 404, headers: [...result.headers], text: await result.text() };
45
+ }
46
+ const text = await readBoundedResponseText(response, { maxBytes: 64 * 1024, label: "API token count", signal });
47
+ if (response.ok) observe(scope, 200);
48
+ return { identity: flight.identity, status: response.status, headers: [...response.headers], text };
49
+ } finally { if (joinable && flights.get(key) === flight) { flights.delete(key);bytes -= flight.bytes; } }
50
+ };
37
51
  try {
38
- if (signal?.aborted) throw signal.reason;
39
- const response = await request(body, { ...options, bodyText: serialized, signal, observeUpstream: false,
40
- onUpstreamStart() { flight.started = true;for (const item of flight.waiters) start(item); } });
41
- if (signal?.aborted) { await response.body?.cancel();throw signal.reason; }
42
- if (response.status === 404) {
43
- await response.body?.cancel();unavailable.set(scope, now());
44
- while (unavailable.size > 128) unavailable.delete(unavailable.keys().next().value);
45
- const result = missed();return { status: result.status, headers: [...result.headers], text: await result.text() };
46
- }
47
- const text = await readBoundedResponseText(response, { maxBytes: 64 * 1024, label: "API token count", signal });
48
- return { status: response.status, headers: [...response.headers], text };
49
- } finally { if (joinable && flights.get(key) === flight) { flights.delete(key);bytes -= size; } }
50
- };
51
- try {
52
- const result = joinable ? await shared.run(flight.key, run, { signal: options.signal }) : await run(options.signal);
53
- options.onCountObservation?.({ shared: flight.shared });
54
- return new Response(result.text || null, { status: result.status, headers: result.headers });
55
- } finally {
56
- flight.waiters.delete(waiter);
57
- if (!flight.waiters.size && joinable && flights.get(key) === flight) { flights.delete(key);bytes -= size; }
52
+ const result = joinable ? await shared.run(flight.key, task, { signal: options.signal }) : await task(options.signal);
53
+ if (result.identity !== identity) {
54
+ options.onCountObservation?.({ waited: true, ...(result.status === 404 ? { cached: true } : {}) });
55
+ if (result.status !== 404) return run(false);
56
+ } else options.onCountObservation?.({ shared: flight.shared });
57
+ return new Response(result.text || null, { status: result.status, headers: result.headers });
58
+ } finally {
59
+ flight.waiters.delete(waiter);
60
+ if (!flight.waiters.size && joinable && flights.get(key) === flight) { flights.delete(key);bytes -= flight.bytes; }
61
+ }
58
62
  }
63
+ return run(!capabilities.has(scope));
59
64
  },
60
65
  };
61
66
  }
@@ -15,16 +15,17 @@ import { apiModelMetadata } from "./api-model-metadata.mjs";
15
15
  import { markRequestObservation, markUpstreamStarted } from "../stream-performance.mjs";
16
16
  import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
17
17
  import { createApiTokenCounter } from "./api-token-count.mjs";
18
+ import { apiModelDisplay } from "../api-model-display.mjs";
18
19
 
19
20
  const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
20
21
  export function apiCatalog(config, env = process.env) {
21
22
  const revision = deploymentRevision(config, env);
22
23
  return config.models.map(model => { const protocol_capabilities = Object.fromEntries(model.protocols.map(protocol => [protocol, resolveModelCapabilities(model, { revision, protocol })]));
23
- const capability = protocol_capabilities[model.protocols.includes("messages") ? "messages" : model.protocols[0]];return ({ id: model.id, name: model.id, publisher: "Unknown",
24
+ const capability = protocol_capabilities[model.protocols.includes("messages") ? "messages" : model.protocols[0]];return ({ id: model.id, name: model.id,
24
25
  supported_endpoints: model.protocols.map(api => paths[api]), model_picker_enabled: true, policy: { state: "enabled" },
25
26
  capability, protocol_capabilities }); });
26
27
  }
27
- export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork } = {}) {
28
+ export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork, modelDisplay = () => ({}) } = {}) {
28
29
  const catalog = apiCatalog(config, env);
29
30
  const fingerprint = config.key_env ? createHash("sha256").update(env[config.key_env] || "").digest("hex") : "";
30
31
  const generation = parseInt(createHash("sha256").update(JSON.stringify(config) + fingerprint).digest("hex").slice(0, 8), 16);
@@ -55,8 +56,11 @@ export function createApiProvider({ config, secrets, env = process.env, platform
55
56
  if (!model?.supported_endpoints.includes(paths[api])) throw accessError("ccdx_api_model_unavailable");return model;
56
57
  };
57
58
  async function request(url, body, options = {}, api = "responses") {
59
+ if (closed) throw accessError("ccdx_api_closed", 503);
58
60
  if (config.key_env && !env[config.key_env]) throw accessError("ccdx_api_environment_key_missing", 503);
59
- const key = config.key_env ? checkedApiKey(env[config.key_env]) : await secrets.get(config.secret_ref), transport = await getNetwork(options.signal);
61
+ const key = config.key_env ? checkedApiKey(env[config.key_env]) : await initialization.run("credential", () => secrets.get(config.secret_ref),
62
+ { signal: options.signal ? AbortSignal.any([options.signal, lifetime.signal]) : lifetime.signal });
63
+ const transport = await getNetwork(options.signal);
60
64
  const headers = { "Content-Type": "application/json", Accept: body?.stream ? "text/event-stream" : "application/json" };
61
65
  headers[api === "messages" && config.auth_header === "x-api-key" ? "x-api-key" : "Authorization"] = api === "messages" && config.auth_header === "x-api-key" ? key : `Bearer ${key}`;
62
66
  if (api === "messages") {
@@ -68,11 +72,15 @@ export function createApiProvider({ config, secrets, env = process.env, platform
68
72
  const constrained = constrainModelRequest(body, capability, api);
69
73
  if (constrained.body !== body) { body = constrained.body;options = { ...options, bodyText: undefined }; }
70
74
  markRequestObservation({ capability_revision: capability?.revision, capability_constraints: constrained.applied.join(",") || "none" });
75
+ markRequestObservation({ context_window_tokens: capability?.values.context_window });
71
76
  }
72
77
  const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
73
78
  if (serialized !== undefined) headers["Content-Length"] = String(Buffer.byteLength(serialized));
74
79
  options.onUpstreamStart?.();
75
- if (body && options.observeUpstream !== false) markUpstreamStarted(body.stream === true);
80
+ if (body && options.observeUpstream !== false) {
81
+ markUpstreamStarted(body.stream === true);
82
+ if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: api === "messages" ? body.max_tokens : api === "chat" ? body.max_completion_tokens : body.max_output_tokens });
83
+ }
76
84
  try {
77
85
  const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
78
86
  if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
@@ -119,7 +127,8 @@ export function createApiProvider({ config, secrets, env = process.env, platform
119
127
  .map(model => ({ ...model, capability: model.protocol_capabilities[family === "claude" ? "messages" : "responses"] })),
120
128
  catalog: () => catalog,
121
129
  publicCatalog(allowed = []) { return { source: "configured", checkedAt: config.checked_at || null, upstreamHost: new URL(config.base_url).hostname,
122
- advertised: catalog.length, models: publicModelCatalog(catalog, { selectable: model => allowed.some(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)),
130
+ advertised: catalog.length, models: publicModelCatalog(catalog.map(model => ({ ...model, ...modelDisplay(model.id) })), { maker: model => model.publisher || model.vendor || null,
131
+ selectable: model => allowed.some(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)),
123
132
  clients: model => allowed.filter(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)) }).map(model => ({ ...model,
124
133
  capability: catalog.find(entry => entry.id === model.id)?.capability, auto_review_efforts: [...(catalog.find(entry => entry.id === model.id)?.protocol_capabilities.responses?.values.reasoning_efforts || [])] })) }; },
125
134
  async discover({ signal } = {}) {
@@ -136,7 +145,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
136
145
  if (!Array.isArray(value.data) || models.length + value.data.length > 500) throw accessError("ccdx_api_catalog_invalid", 502);
137
146
  for (const model of value.data) { if (!model || typeof model.id !== "string" || !/^[\w][\w./:@+-]{0,159}$/.test(model.id) || model.id.includes("..") || model.id.includes("//") || ids.has(model.id)) throw accessError("ccdx_api_catalog_invalid", 502);ids.add(model.id); }
138
147
  // A catalog listing is not evidence that every model supports every API.
139
- models.push(...value.data.map(model => ({ id: model.id, metadata: apiModelMetadata(model, { checked_at, deployment: deploymentRevision(config, env) }), protocols: Array.isArray(model.supported_endpoints)
148
+ models.push(...value.data.map(model => ({ id: model.id, display: apiModelDisplay(model), metadata: apiModelMetadata(model, { checked_at, deployment: deploymentRevision(config, env) }), protocols: Array.isArray(model.supported_endpoints)
140
149
  ? Object.entries(paths).filter(([, endpoint]) => model.supported_endpoints.includes(endpoint) || model.supported_endpoints.includes(endpoint.slice(3))).map(([api]) => api).filter(api => config.endpoints[api]) : [] })));
141
150
  if (value.has_more !== true) return models;
142
151
  // Follow only the native cursor on the configured origin, never an
@@ -118,7 +118,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
118
118
  const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
119
119
  if (serialized !== undefined) requestHeaders["Content-Length"] = String(Buffer.byteLength(serialized));
120
120
  options.onUpstreamStart?.();
121
- if (body) markUpstreamStarted(body.stream === true);
121
+ if (body) { markUpstreamStarted(body.stream === true);if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: endpoint.includes("messages") ? body.max_tokens : body.max_output_tokens }); }
122
122
  try {
123
123
  const send = fetchImpl || await transport(options.signal);
124
124
  const response = await send(`${M365_API_BASE}${endpoint}`, { method: body ? "POST" : "GET", headers: requestHeaders,
@@ -102,10 +102,16 @@ export function protectInstallation({ target, prefix, platform = process.platfor
102
102
  if (!target || !prefix) return { commit() {}, rollback() {} };
103
103
  const parent = path.dirname(target);fs.mkdirSync(parent, { recursive: true });
104
104
  const lock = path.join(parent, ".ccdx-install.lock");let fd;
105
- try { fd = fs.openSync(lock, "wx", 0o600); } catch { throw new Error("Another install may be running. Check the CCDX install lock before retrying."); }
105
+ try { fd = fs.openSync(lock, "wx", 0o600); }
106
+ catch (error) {
107
+ if (error.code === "EEXIST") throw new Error(`Another install may be running. CCDX install lock: ${lock}. Inspect its owner and .ccdx-backup-* in ${parent} before recovery; do not remove an active install lock.`, { cause: error });
108
+ throw new Error(`Cannot create the CCDX install lock at ${lock} (${error.code || "I/O error"}). Check directory permissions and free space; no installation was started.`, { cause: error });
109
+ }
106
110
  let backup;
107
- try { backup = fs.mkdtempSync(path.join(parent, ".ccdx-backup-")); }
108
- catch (error) { fs.closeSync(fd);fs.unlinkSync(lock);throw error; }
111
+ try {
112
+ backup = fs.mkdtempSync(path.join(parent, ".ccdx-backup-"));
113
+ fs.writeFileSync(fd, JSON.stringify({ version: 1, pid: process.pid, created_at: new Date().toISOString(), backup }) + "\n");
114
+ } catch (error) { if (backup) fs.rmSync(backup, { recursive: true, force: true });fs.closeSync(fd);fs.unlinkSync(lock);throw error; }
109
115
  const entries = [target, ...["ccdx", "codex-copilot-dx"].flatMap(name => platform === "win32"
110
116
  ? [name, `${name}.cmd`, `${name}.ps1`].map(file => path.join(prefix, file)) : [path.join(prefix, "bin", name)])];
111
117
  const saved = [];
@@ -2,6 +2,7 @@ import { terminalCell } from "./terminal-text.mjs";
2
2
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
3
3
  import { currentRequestContext } from "./request-context.mjs";
4
4
  import { isProviderId } from "./provider-metadata.mjs";
5
+ import { transportErrorDetails } from "./operation-error.mjs";
5
6
 
6
7
  const DEFAULT_RECENT_FAILURES = 10;
7
8
 
@@ -129,6 +130,7 @@ export function requestOptionsEvidence(body) {
129
130
  if (["auto", "default", "flex", "priority", "scale"].includes(body.service_tier)) result.service_tier = body.service_tier;
130
131
  if (["text", "json_object", "json_schema"].includes(body.text?.format?.type)) result.output_format = body.text.format.type;
131
132
  if (Number.isSafeInteger(body.max_output_tokens) && body.max_output_tokens >= 0) result.max_output_tokens = body.max_output_tokens;
133
+ if (Number.isSafeInteger(body.max_tokens) && body.max_tokens >= 0) result.max_tokens = body.max_tokens;
132
134
  if (Array.isArray(body.tools)) result.tools = body.tools.length;
133
135
  if (Array.isArray(body.input)) result.input_items = body.input.length;
134
136
  return result;
@@ -144,15 +146,16 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
144
146
  return {
145
147
  record(details) {
146
148
  all.record(details);
147
- const category = details.route === "messages_count_tokens" ? "capability"
149
+ const accessNotice = details.reason === "ccdx_model_not_selected" || details.reason === "ccdx_client_source_disabled";
150
+ const category = accessNotice || details.route === "messages_count_tokens" ? "capability"
148
151
  : ["responses", "responses_compact", "messages"].includes(details.route) ? "inference"
149
152
  : details.route === "image_mcp" && details.http_status === 405 ? "protocol"
150
153
  : details.route === "not_found" ? "route" : "other";
151
154
  counts[category]++;
152
- if (category === "inference" || category === "other") actionable.record(details);
155
+ if ((category === "inference" || category === "other") && !accessNotice) actionable.record(details);
153
156
  if (category === "capability") {
154
157
  capability.record(details);
155
- if (![404, 405, 501].includes(details.http_status)) actionable.record(details);
158
+ if (!accessNotice && ![404, 405, 501].includes(details.http_status)) actionable.record(details);
156
159
  }
157
160
  if (category === "protocol") protocol.record(details);
158
161
  if (category === "route") routes.record(details);
@@ -165,13 +168,17 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
165
168
 
166
169
  export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers,
167
170
  error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
168
- application, reason, capability_cached, shared_upstream }) {
171
+ application, reason, capability_cached, shared_upstream, transport }) {
172
+ if (!reason && code === "ccdx_client_source_disabled" && upstream_attempts === 0 && origin !== "upstream_http") {
173
+ reason = code;origin = "client_validation";
174
+ }
169
175
  const reasons = { ccdx_model_not_selected: "This model is not selected for this app.",
170
176
  ccdx_model_ambiguous: "This model name matches multiple sources. Select its source-specific entry.",
171
177
  ccdx_model_catalog_unavailable: "The selected model is not currently available in its source catalog.",
172
178
  ccdx_client_source_disabled: "This app or its model source is turned off." };
173
179
  const message = (Object.hasOwn(reasons, reason) ? reasons[reason] : null) || (route === "messages_count_tokens" && statusCode === 404 ? "The source's token-count endpoint returned HTTP 404. Message generation is separate."
174
- : origin === "client_validation" ? "The request was rejected locally before an upstream call."
180
+ : code === "ccdx_api_network_unavailable" ? "Connection to the model source failed."
181
+ : origin === "client_validation" ? "The request was rejected locally before an upstream call."
175
182
  : error_body === "empty" ? "Upstream returned no error details." : "HTTP request failed; original response was preserved.");
176
183
  const details = responseFailureDetails({ model, error: { code: typeof code === "string" && /^[a-z\d_.:-]{1,80}$/i.test(code) ? code : `http_${statusCode}`,
177
184
  message } }, "http.error", { headers, provider });
@@ -186,5 +193,6 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
186
193
  ...(["codex_app", "codex_cli", "codex", "claude_app", "claude_code", "claude", "api"].includes(application) ? { application } : {}),
187
194
  ...(Object.hasOwn(reasons, reason) ? { reason } : {}),
188
195
  ...(capability_cached === true ? { capability_cached: true } : {}), ...(shared_upstream === true ? { shared_upstream: true } : {}),
196
+ ...(transport ? { transport: transportErrorDetails({ transport }) } : {}),
189
197
  ...(Number.isSafeInteger(upstream_attempts) ? { upstream_attempts } : {}) };
190
198
  }
@@ -208,6 +208,7 @@ export function createResponsesHandler(options) {
208
208
  abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
209
209
  parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
210
210
  observeRequestedModel(parsed);
211
+ markRequestObservation({ max_output_tokens_requested: parsed?.max_output_tokens });
211
212
  const selectedProvider = options.resolveProvider?.(parsed, req);
212
213
  if (selectedProvider) {
213
214
  provider = selectedProvider;modelRegistry = provider.registry;
@@ -492,6 +493,7 @@ export function createResponsesCompactHandler(options) {
492
493
  abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
493
494
  const parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
494
495
  observeRequestedModel(parsed);
496
+ markRequestObservation({ max_output_tokens_requested: parsed?.max_output_tokens });
495
497
  const selectedProvider = options.resolveProvider?.(parsed, req);
496
498
  if (selectedProvider) {
497
499
  provider = selectedProvider;modelRegistry = provider.registry;
@@ -63,7 +63,7 @@ export function providerStartupSummary(data = {}) {
63
63
  const connections = data.providers.connections;
64
64
  if (connections?.managed) {
65
65
  const enabled = connections.providers.filter(provider => provider.enabled);
66
- const states = { configured: "configured", not_configured: "not configured", not_installed: "not installed", preserved: "custom settings kept", configuration_unavailable: "config unavailable", partially_preserved: "partly configured", unavailable: "source unavailable" };
66
+ const states = { configured: "configured", paused: "paused", disabled: "off", not_configured: "not configured", not_installed: "not installed", preserved: "custom settings kept", configuration_unavailable: "config unavailable", partially_preserved: "partly configured", unavailable: "source unavailable" };
67
67
  const sourceLines = enabled.map(provider => `${terminalCell(provider.name)} / ${provider.builtin ? provider.id === "m365" ? terminalCell(connections.m365_state) : "sign-in checked separately" : `${provider.model_count} configured models`}`);
68
68
  const claudeLines = connections.clients.filter(client => client.id !== "codex").map(client => `${client.name}: ${!client.enabled ? "off" : client.source ? states[client.setup] || "not checked" : "paused"}`);
69
69
  return { catalogs: `${enabled.length} enabled source${enabled.length === 1 ? "" : "s"}`, claude: claudeLines.join(" / "), sourceLines, claudeLines,
@@ -249,7 +249,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
249
249
  let headersAt = null;
250
250
  let lastActivityAt = null;
251
251
  let terminalAt = null;
252
- const context = { payload_bytes: null, images: null, input_tokens: null, context_window_tokens: null };
252
+ const context = { payload_bytes: null, images: null, input_tokens: null, context_window_tokens: null, output_tokens: null, max_output_tokens_requested: null, max_output_tokens_sent: null };
253
+ let stopReason = null;
253
254
  const elapsed = (time) => time === null ? null : Number(Math.max(0, time - requestStartedAt).toFixed(1));
254
255
  if (activeRequests.size < MAX_ACTIVE_REQUESTS) activeRequests.set(activeId, () => ({
255
256
  request_id: safeRequestId, application: client, route: routeName, provider, model, phase,
@@ -337,19 +338,20 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
337
338
  setErrorOrigin(value) {
338
339
  if (TERMINAL_ORIGINS.has(value)) errorOrigin = value;
339
340
  },
340
- terminal(outcome, { model: terminalModel, origin, reason } = {}) {
341
+ terminal(outcome, { model: terminalModel, origin, reason, stopReason: stopped } = {}) {
341
342
  if (finished || terminalOutcome || !TERMINAL_OUTCOMES.includes(outcome)) return;
342
343
  terminalOutcome = outcome;
343
344
  terminalAt = now();
344
345
  if (terminalModel !== undefined) model = modelLabel(terminalModel);
345
346
  if (TERMINAL_ORIGINS.has(origin)) terminalOrigin = origin;
346
347
  if (outcome === "incomplete") incompleteReason = INCOMPLETE_REASONS.has(reason) ? reason : "other";
348
+ if (["end_turn", "max_tokens", "tool_use", "stop_sequence", "pause_turn", "refusal", "model_context_window_exceeded"].includes(stopped)) stopReason = stopped;
347
349
  if (outcome !== "completed") failed = true;
348
350
  },
349
351
  fail() {
350
352
  failed = true;
351
353
  },
352
- finish({ failed: finishFailed = false, aborted = false, statusCode = 0 } = {}) {
354
+ finish({ failed: finishFailed = false, aborted = false, statusCode = 0, rejectionReason } = {}) {
353
355
  if (finished) return;
354
356
  if (!sourceStats) assignProvider("unknown");
355
357
  finished = true;
@@ -381,6 +383,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
381
383
  recentRequests.push({
382
384
  request_id: safeRequestId, application: client,
383
385
  at, route: routeName, model, outcome, origin, phase,
386
+ ...(["ccdx_model_not_selected", "ccdx_client_source_disabled"].includes(rejectionReason) ? { rejection_reason: rejectionReason } : {}),
387
+ ...(stopReason ? { stop_reason: stopReason } : {}),
384
388
  ...(provider ? { provider } : {}),
385
389
  empty_stream_completion: emptyStreamCompletion,
386
390
  failed: failed || aborted || (terminalOutcome !== null && terminalOutcome !== "completed"),