codex-copilot-dx 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -57,6 +57,7 @@ Model availability depends on your account and service. Microsoft 365 also requi
57
57
  | Inspect compression | `ccdx compact status` / `ccdx compact enable` / `ccdx compact disable` |
58
58
  | Inspect failures | `ccdx requests --failed` |
59
59
  | Inspect observed tool calls | `ccdx requests tools` / `ccdx requests tools --active` |
60
+ | Inspect active model requests | `ccdx requests --active` |
60
61
  | Capture one upstream error | `ccdx requests diagnose --source api_work --model model-id --yes` |
61
62
  | Read usage | `ccdx usage` / `ccdx usage --provider google --days 7` / `ccdx usage --purpose diagnostic` / `ccdx usage --scope run` |
62
63
  | Inspect preferences | `ccdx config show --effective` |
@@ -683,6 +683,12 @@ load only when requested. Allowed function lists retain their
683
683
  restriction and returned Chat calls are checked before completion. Chat cache
684
684
  fields are forwarded only when the catalog explicitly advertises each field.
685
685
 
686
+ Loaded Carbon tool declarations use last-value replacement by type/namespace/name while retaining the first offered Map slot and alias. The initial list keeps its conflicting-definition check; input-carried additions and search results resolve against the effective inventory. This adopts the narrow dynamic-declaration behavior from [Floway](https://github.com/Menci/Floway/commit/2e5a4bed646f02e1054e71089232c63036c21f2f).
687
+
688
+ `model-catalog.mjs` normalizes one source/account list at ingestion and public projection. Unique lists retain their original reference. Duplicate IDs retain order and explicit first values, including false and empty arrays; copy-on-write nested merges fill only absent/null/empty-string metadata. Copilot live reads, old cache reads/writes, M365 directories and serial API discovery use this rule. API limits still count raw entries and repeated pagination cursors fail. Credentials, configured deployments and cross-source lists never enter the merge. The bounded catalog change follows [Magpie's directory normalization](https://github.com/yetone/magpie/commit/97e6ac36c9704455e2505d58f673308c0611edad).
689
+
690
+ The cache-preservation principle from [LiteLLM](https://github.com/BerriAI/litellm/pull/51796) applies to CCDX's existing Responses-to-Chat direction, without adding a reverse bridge. Catalog-advertised cache fields gate block conversion, optional caller cache options remain separately gated, and leading system order remains unchanged. Native source protocols retain their fields. Mixed thought/answer and HTTP-200 terminal-error cases remain explicit stream-contract coverage. Following [Magpie's sealed-task protection](https://github.com/yetone/magpie/commit/c747ecfa68eb095a2269771f1b6382205e9facbd), encrypted retry cleanup never strips agent-message bodies; Chat rejects opaque task content before a request is sent.
691
+
686
692
  For an explicit root-combiner schema validation failure, the custom Messages
687
693
  provider may send a bounded, model-facing object schema while retaining the
688
694
  original validator for the response. Guarded tool frames are buffered until the
@@ -1234,4 +1240,4 @@ The implementation takes the native/gateway-state ownership separation from [Mag
1234
1240
 
1235
1241
  `tool-activity.mjs` stores bounded, memory-only metadata behind each stream-performance observer. Existing parsed Responses items, Messages blocks and Gemini function calls supply tool names and scoped identifiers; no argument or output body is copied. The existing session/profile HMAC and application label isolate result matching. Results match call IDs, with a unique-name-only fallback for Gemini. Request completion changes generated calls to waiting, never to successful execution. Observable returned results, source failures and cancellation terminate the corresponding observations. Live response activity renews preparing observations with at most one notification per second per request. Missing evidence becomes unknown after 90 seconds, with a bounded late-result window. Snapshot reads perform lazy retention cleanup; there is no server polling loop.
1236
1242
 
1237
- The WebUI consumes this metadata through the existing activity subscription. `dashboard/tool-activity.js` draws only the selected style, caches layout/theme measurements, caps drawing at 30 fps and DPR 1.5, pauses hidden/off-screen/reduced-motion views, and stops terminal cues within 0.9 seconds. Local deadline timers stop stale activity even when the stream has no new events. Native controls, theme variables and the language dictionary preserve the existing UI contract. The read-only `requests tools` grammar also drives TUI discovery.
1243
+ The WebUI consumes this metadata through the existing activity subscription. `dashboard/tool-activity.js` draws only the selected style, caches layout/theme measurements, caps drawing at 30 fps and DPR 1.5, pauses hidden/off-screen/reduced-motion views, and stops terminal cues within 0.9 seconds. Beam ring is the default; grid, busy pulse, fast streaks and assembly line are alternatives. Removed styles fall back to the default and Off retains state text. With no pending calls, conversation-purpose active requests supply processing/reply cues; internal diagnostics and terminal requests are excluded. Non-live request snapshots expire after six seconds. Local deadline timers stop stale activity even when the stream has no new events. Native controls, theme variables and the language dictionary preserve the existing UI contract. Existing `requests --active` and `requests tools` grammar also drive TUI discovery.
package/docs/REFERENCE.md CHANGED
@@ -116,11 +116,11 @@ Each protocol observer retains at most 64 series of 64 request points and 16 com
116
116
 
117
117
  ## Observed tool calls
118
118
 
119
- **Requests → Tool calls** uses the existing activity stream for Codex, Claude and Antigravity. Choose Grid, Beam ring, Orbit rings, Woven field or Off; this browser remembers the choice. Captions change with observed call preparation, waiting and returned results. Motion runs at a faster presentation cadence, independent of event frequency; it is not a progress percentage or a call counter. System reduced motion, hidden/off-screen views and Off stop continuous drawing. Returned results have at most a 0.9-second finish cue; failure, cancellation and unavailable evidence stop continuous motion.
119
+ **Requests → Tool and agent activity** uses the existing activity stream for Codex, Claude and Antigravity. Beam ring is the default; choose Grid, Busy pulse, Fast streaks, Assembly line or Off. This browser remembers valid choices; removed Orbit rings and Woven field choices fall back to Beam ring. Captions change with observed call preparation, waiting and returned results. When no tools are pending, active conversation requests show processing or reply generation. These are observed gateway request phases, not a count of native subagents. Motion runs at a faster presentation cadence, independent of event frequency; it is not a progress percentage or a call counter. System reduced motion and hidden/off-screen views pause continuous drawing. Off stops drawing and keeps the status text. Returned results have at most a 0.9-second finish cue; failure, cancellation and unavailable evidence stop continuous motion.
120
120
 
121
121
  Calls are correlated using their IDs and the existing app/profile/session scope. A model emitting a tool call does not prove that the client executed it. Only a matching returned result ends the wait; ambiguous name-only Gemini results stay unconfirmed. Without a reliable session, completed requests show unconfirmed tool state. After 90 seconds without observable tool or response activity, the UI pauses and shows that fresh status is needed. Late results can update retained unconfirmed observations for another five minutes. These display deadlines never cancel tools or change source timeouts.
122
122
 
123
- The service retains at most 128 metadata observations per protocol observer, shows at most 32, and captures at most 32 calls per request. Finished observations remain for 15 seconds. It keeps safe tool names and local display IDs in memory, not arguments, outputs or raw conversation/call IDs. Input correlation checks a bounded recent suffix rather than scanning a transcript. It adds no provider calls, tokenization, activity connections or polling. `ccdx requests tools --format json` and the TUI Requests menu expose the same observations; `--active` selects preparing/waiting calls. Restarting clears these diagnostic observations.
123
+ The service retains at most 128 metadata observations per protocol observer, shows at most 32, and captures at most 32 calls per request. Finished observations remain for 15 seconds. It keeps safe tool names and local display IDs in memory, not arguments, outputs or raw conversation/call IDs. Input correlation checks a bounded recent suffix rather than scanning a transcript. It adds no provider calls, tokenization, activity connections or polling. `ccdx requests tools --format json` and the TUI Requests menu expose the same tool observations; `--active` selects preparing/waiting calls. `ccdx requests --active` reads active model requests. The motion choice is a browser preference. Restarting clears these diagnostic observations.
124
124
 
125
125
  ## Sources and client access
126
126
 
@@ -138,6 +138,8 @@ Manual APIs require HTTPS. Codex requires Responses; Claude requires Messages. C
138
138
 
139
139
  A running request stays with its original source, credential revision and capabilities. Refreshing a catalog does not select models or change defaults. Failed reads keep last-good data with failure evidence; they do not trigger inference, re-login or source switching. Normal API refresh uses a 30-minute cache and a one-minute minimum interval after explicit reads or failures.
140
140
 
141
+ Within one source/account, repeated upstream model IDs keep their first position and existing values; later entries fill missing metadata. Explicit false values and empty capability arrays remain authoritative. Live catalogs, compatible old caches and public model details use this normalization. Source and account boundaries stay separate, and duplicate deployments in user configuration remain invalid. Existing source-model CLI/TUI commands read the same normalized catalogs.
142
+
141
143
  Codex selections containing only GitHub models keep native OpenAI mode and readable names. Other selections use the client's private local gateway credential. Paused access is rejected before credential validation. CCDX does not write or clear native ChatGPT sign-in data. When models are missing after a client update, check the selected models and run `ccdx doctor`; fully quit and reopen the app before changing credentials.
142
144
 
143
145
  Old conversations keep their recorded provider identity. Codex 0.166 requires the currently selected provider to match that identity; a per-resume override does not bypass this check. Continue a legacy custom-provider chat with its original provider selected. CCDX retains the inactive, unchanged legacy provider table and does not silently rewrite chat metadata or switch the global native default back to a custom provider.
@@ -868,6 +870,8 @@ Changing the model or transport of a continuation can require removing incompati
868
870
 
869
871
  Native Responses forwards Codex `agent_message` items unchanged. When a model requires Chat Completions, CCDX frames them as messages from another agent, not human input or approval, retaining author/recipient, typed text/refusal/reasoning and representable image/screenshot content. Content unsupported by Chat, including file, audio or opaque encrypted parts, receives an explicit compatibility error instead of being serialized into ordinary text. This projection does not introduce another model request or change native Responses, Fast, Auto-review or compaction routing.
870
872
 
873
+ Encrypted-state cleanup preserves complete agent messages, including their sealed task body. An upstream refusal never authorizes removing that task body to retry only its visible header.
874
+
871
875
  GitHub Copilot's `gemini-4-carbon` uses Chat Completions. CCDX maps Codex custom,
872
876
  namespaced and client-side tool-search calls to function tools and restores their
873
877
  original identities in the reply and conversation history. The upstream receives
@@ -875,6 +879,10 @@ ordinary function tools; free-form grammar constraints are included in the tool
875
879
  description rather than enforced by the Chat protocol. Other models retain their
876
880
  existing routing and compatibility checks.
877
881
 
882
+ For Carbon, input `additional_tools` and client `tool_search_output` declarations take effect in order. A later loaded definition replaces the same type/namespace/name without changing its original offered slot or alias. Explicit tool-choice restrictions still apply; conflicting definitions inside the initial tool list remain invalid.
883
+
884
+ On the existing Responses-to-Chat route, per-model catalog flags under `capabilities.supports` control cache forwarding. `cache_control: true` preserves caller cache controls; `prompt_cache_breakpoint: true` preserves explicit breakpoints and maps caller cache controls to explicit breakpoints without inventing a TTL. `prompt_cache_options: true` separately permits caller request options. Messages keep their order, including marked system messages. Unmarked requests and undeclared fields keep their existing behavior. Native Responses and Messages retain their own cache fields. These controls do not establish a measured cache hit or latency benefit.
885
+
878
886
  Carbon's standalone web search uses the current GitHub Copilot account. Only
879
887
  search queries and requested constraints are sent to its search endpoint; the
880
888
  conversation input and ChatGPT credentials are not forwarded. With live web
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.4.1",
3
+ "version": "1.4.2",
4
4
  "description": "Local gateway for Codex, Claude and Gemini Antigravity with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/adapter.mjs CHANGED
@@ -5,6 +5,7 @@ import { createNativeImagesHandler } from "./native-images.mjs";
5
5
  import { defaultCopilotClient } from "./copilot.mjs";
6
6
  import { buildCodexModelResponse } from "./codex-model-catalog.mjs";
7
7
  import { isValidModelList } from "./model-cache.mjs";
8
+ import { normalizeModelList } from "./model-catalog.mjs";
8
9
  import {
9
10
  ADAPTER_STATUS_PATH,
10
11
  classifyAdapterRoute,
@@ -148,7 +149,7 @@ async function sendModelList(res, models, {
148
149
 
149
150
  async function sendLastKnownGoodModels(res, modelRegistry, options = {}) {
150
151
  if (!isValidModelList(modelRegistry?.models) || res.destroyed || res.writableEnded) return false;
151
- await sendModelList(res, modelRegistry.models, {
152
+ await sendModelList(res, normalizeModelList(modelRegistry.models), {
152
153
  ...options,
153
154
  headers: { "X-CCDX-Model-Source": "last-known-good" },
154
155
  });
@@ -415,7 +416,10 @@ export function createAdapterHandler(options = {}) {
415
416
  abort.clearTimeout();
416
417
  if (status >= 200 && status < 300) {
417
418
  let models;
418
- try { models = JSON.parse(body); } catch {}
419
+ try {
420
+ const parsed = JSON.parse(body);models = normalizeModelList(parsed);
421
+ if (models !== parsed) body = JSON.stringify(models);
422
+ } catch {}
419
423
  if (isValidModelList(models)) {
420
424
  if (selectedRegistry) {
421
425
  selectedRegistry.models = models;
@@ -125,9 +125,11 @@ export function prepareCarbonToolBridge(body, currentInputStart = 0) {
125
125
  parameters: structuredClone(tool.parameters), strict: tool.strict };
126
126
  }
127
127
  const existing = offered.get(entry.key);
128
- if (existing && JSON.stringify(existing) !== JSON.stringify(converted)) {
128
+ if (existing && !loaded && JSON.stringify(existing) !== JSON.stringify(converted)) {
129
129
  throw requestError("Carbon received conflicting definitions for the same tool");
130
130
  }
131
+ // Loaded Responses declarations replace the value without moving its slot
132
+ // or changing the alias used by earlier calls and tool-choice constraints.
131
133
  offered.set(entry.key, converted);
132
134
  }
133
135
 
@@ -1,4 +1,5 @@
1
1
  import { createCopilotTokenSession } from "./copilot-token-session.mjs";
2
+ import { normalizeModelList, uniqueModelEntries } from "./model-catalog.mjs";
2
3
  import { MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "./http-transport.mjs";
3
4
  import { prepareResponsesPayload, summarizeReqBody } from "./image-optimization.mjs";
4
5
  import { debugLog } from "./log.mjs";
@@ -66,7 +67,7 @@ export function createCopilotClientRuntime({
66
67
  const data = Array.isArray(models) ? models : models?.data;
67
68
  if (!Array.isArray(data)) return false;
68
69
  const next = new Map();
69
- for (const model of data) {
70
+ for (const model of uniqueModelEntries(data)) {
70
71
  const id = String(model?.id || "").trim();
71
72
  if (id && Array.isArray(model?.supported_endpoints)) next.set(id, [...model.supported_endpoints]);
72
73
  }
@@ -120,12 +121,16 @@ export function createCopilotClientRuntime({
120
121
  headers,
121
122
  signal,
122
123
  }, { fetchImpl, ...retryOptions });
123
- const body = await readBoundedResponseText(response, {
124
+ let body = await readBoundedResponseText(response, {
124
125
  maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES,
125
126
  label: "Copilot model catalog",
126
127
  });
127
128
  if (response.ok) {
128
- try { cacheModelEndpoints(JSON.parse(body)); } catch {}
129
+ try {
130
+ const parsed = JSON.parse(body), models = normalizeModelList(parsed);
131
+ cacheModelEndpoints(models);
132
+ if (models !== parsed) body = JSON.stringify(models);
133
+ } catch {}
129
134
  }
130
135
  return { status: response.status, body };
131
136
  }
@@ -370,9 +370,9 @@
370
370
  <details id="flow-active" class="tool-details"><summary id="flow-active-title" data-i18n="flow_active_requests">Active requests</summary><div class="table-wrap"><table><thead><tr><th data-i18n="client">App</th><th data-i18n="source">Source</th><th data-i18n="model">Model</th><th data-i18n="state">State</th><th data-i18n="flow_elapsed">Elapsed</th><th data-i18n="attempts">Attempts</th></tr></thead><tbody id="flow-active-body"></tbody></table></div></details>
371
371
  </section>
372
372
  <section id="tool-activity" class="panel dashboard-section" aria-labelledby="tool-title" data-paused="true">
373
- <div class="panel-heading"><h2 id="tool-title" data-i18n="tool_heading">TOOL CALLS</h2><label class="tool-style" for="tool-style"><span data-i18n="tool_style">Style</span><select id="tool-style"><option value="grid" data-i18n="tool_style_grid">Grid</option><option value="halo" data-i18n="tool_style_halo">Beam ring</option><option value="orbit" data-i18n="tool_style_orbit">Orbit rings</option><option value="weave" data-i18n="tool_style_weave">Woven field</option><option value="off" data-i18n="tool_style_off">Off</option></select></label></div>
374
- <div id="tool-stage" class="tool-stage" data-style="grid">
375
- <div class="tool-visual"><div class="tool-orbit"><canvas id="tool-canvas" role="img" data-i18n-label="tool_heading" aria-label="Tool calls"></canvas></div><p class="tool-narration"><span id="tool-state" role="status" aria-live="polite" data-i18n="flow_status_unknown">Waiting for a fresh status</span><span id="tool-cursor" aria-hidden="true" hidden> ···</span></p></div>
373
+ <div class="panel-heading"><h2 id="tool-title" data-i18n="tool_heading">TOOL AND AGENT ACTIVITY</h2><label class="tool-style" for="tool-style"><span data-i18n="tool_style">Style</span><select id="tool-style"><option value="halo" data-i18n="tool_style_halo">Beam ring</option><option value="grid" data-i18n="tool_style_grid">Grid</option><option value="busy" data-i18n="tool_style_busy">Busy pulse</option><option value="speed" data-i18n="tool_style_speed">Fast streaks</option><option value="assembly" data-i18n="tool_style_assembly">Assembly line</option><option value="off" data-i18n="tool_style_off">Off</option></select></label></div>
374
+ <div id="tool-stage" class="tool-stage" data-style="halo">
375
+ <div class="tool-visual"><div class="tool-orbit"><canvas id="tool-canvas" role="img" data-i18n-label="tool_heading" aria-label="Tool and agent activity"></canvas></div><p class="tool-narration"><span id="tool-state" role="status" aria-live="polite" data-i18n="flow_status_unknown">Waiting for a fresh status</span><span id="tool-cursor" aria-hidden="true" hidden> ···</span></p></div>
376
376
  <div class="tool-content"><p id="tool-context" class="tool-context" hidden></p><div id="tool-list"></div><p id="tool-more" class="hint" hidden></p><details id="tool-details" class="tool-details tool-technical" hidden><summary data-i18n="tool_details">Call details</summary><div id="tool-technical"></div></details></div>
377
377
  </div>
378
378
  </section>
@@ -1,11 +1,12 @@
1
1
  (() => {
2
2
  const translations = {
3
- "tool_heading": ["Tool calls","工具调用"],
3
+ "tool_heading": ["Tool and agent activity","工具与代理活动"],
4
4
  "tool_style": ["Style","样式"],
5
5
  "tool_style_grid": ["Grid","格子进度条"],
6
6
  "tool_style_halo": ["Beam ring","光束圆环"],
7
- "tool_style_orbit": ["Orbit rings","轨道圆环"],
8
- "tool_style_weave": ["Woven field","编织光场"],
7
+ "tool_style_busy": ["Busy pulse","忙碌脉冲"],
8
+ "tool_style_speed": ["Fast streaks","疾速流光"],
9
+ "tool_style_assembly": ["Assembly line","装配流水线"],
9
10
  "tool_style_off": ["Off","关闭"],
10
11
  "tool_preparing": ["Preparing a tool call","正在准备调用"],
11
12
  "tool_preparing_many": ["Preparing {count} calls","并行准备 {count} 项调用"],
@@ -14,6 +15,12 @@
14
15
  "tool_failed": ["A tool call failed","调用失败"],
15
16
  "tool_cancelled": ["Request cancelled","请求已取消"],
16
17
  "tool_idle": ["Waiting for the next call","等待下一次调用"],
18
+ "tool_processing": ["Processing the request","正在处理请求"],
19
+ "tool_responding": ["Generating a reply","正在生成回复"],
20
+ "tool_requests_many": ["Processing {count} requests","正在处理 {count} 个请求"],
21
+ "tool_processing_action": ["Process request","处理请求"],
22
+ "tool_response_action": ["Generate reply","生成回复"],
23
+ "tool_row_active": ["Active","进行中"],
17
24
  "tool_groups": ["{count} app and model groups","{count} 个应用及模型分组"],
18
25
  "tool_more": ["{count} more observations in call details","另有 {count} 项观测,见调用详情"],
19
26
  "tool_details": ["Call details","调用详情"],
@@ -331,7 +331,7 @@
331
331
  }
332
332
  function renderActivity(data) {
333
333
  globalThis.ccdxDashboardActivity?.update(data.model_activity, { live: true });
334
- globalThis.ccdxDashboardFlow?.update(data, { live: true });globalThis.ccdxToolActivity?.update(data);
334
+ globalThis.ccdxDashboardFlow?.update(data, { live: true });globalThis.ccdxToolActivity?.update(data, { live: true });
335
335
  text("version", `v${data.version || "?"}`);
336
336
  text("uptime", "pid_pid_uptime_duration", { pid: number(data.pid), duration: duration(data.uptime_ms) });
337
337
  text("requests", number(data.requests?.total));
@@ -1,15 +1,16 @@
1
1
  (() => {
2
2
  const root = document.getElementById("tool-activity");if (!root) return;
3
3
  const el = id => document.getElementById(id), canvas = el("tool-canvas"), ctx = canvas.getContext?.("2d");
4
- const styles = new Set(["grid", "halo", "orbit", "weave", "off"]), storageKey = "ccdx.dashboard.toolMotionStyle";
4
+ const styles = new Set(["halo", "grid", "busy", "speed", "assembly", "off"]), storageKey = "ccdx.dashboard.toolMotionStyle";
5
5
  const pending = state => ["preparing", "waiting"].includes(state);
6
6
  const phrase = (key, values = {}) => globalThis.ccdxLanguage.format(key, values);
7
7
  const text = (id, key, values) => globalThis.ccdxLanguage.set(el(id), key, values);
8
- const state = { scene: "idle", style: "grid", intensity: .8, reduce: false };
8
+ const state = { scene: "idle", style: "halo", intensity: .8, reduce: false };
9
9
  try { const saved = localStorage.getItem(storageKey);if (styles.has(saved)) state.style = saved; } catch {}
10
10
  const motion = globalThis.matchMedia?.("(prefers-reduced-motion: reduce)") || { matches: false, addEventListener() {} };
11
11
  let records = [], fresh = false, supported = false, visible = true, raf = 0, last = 0, start = performance.now(), expiry = null;
12
- let signature = "", box = { width: 0, height: 0 }, color = "", omitted = 0;
12
+ let signature = "", box = { width: 0, height: 0 }, color = "", omitted = 0, requests = [], requestDeadline = 0;
13
+ const animating = () => ["calling", "parallel", "waiting", "processing", "responding"].includes(state.scene);
13
14
  const shown = () => document.visibilityState === "visible" && !root.closest("[hidden]") && visible;
14
15
  function measure() {
15
16
  box = canvas.getBoundingClientRect();color = getComputedStyle(document.documentElement).getPropertyValue("--accent").trim();
@@ -21,8 +22,8 @@
21
22
  if(canvas.width!==Math.round(w*dpr)||canvas.height!==Math.round(h*dpr)){canvas.width=Math.round(w*dpr);canvas.height=Math.round(h*dpr);}
22
23
  ctx.setTransform(dpr,0,0,dpr,0,0);ctx.clearRect(0,0,w,h);
23
24
  const cx=w/2,cy=h/2,r=Math.min(w,h)*.31;
24
- const reduced=motion.matches||state.reduce,t=reduced?0:(now-start)/1000,active=['calling','parallel'].includes(state.scene),waiting=state.scene==='waiting',returned=state.scene==='returned';
25
- const quiet=state.scene==='idle'||state.scene==='responding',power=quiet?.12:waiting?.5:returned?.5:state.intensity;
25
+ const reduced=motion.matches||state.reduce,t=reduced?0:(now-start)/1000,active=['calling','parallel','processing','responding'].includes(state.scene),waiting=state.scene==='waiting',returned=state.scene==='returned';
26
+ const quiet=!active&&!waiting&&!returned,power=quiet?.12:waiting?.5:returned?.5:state.intensity;
26
27
  ctx.strokeStyle=color;ctx.fillStyle=color;ctx.lineWidth=.8;
27
28
  function arc(radius,a,b,alpha){ctx.globalAlpha=alpha;ctx.beginPath();ctx.arc(cx,cy,radius,a,b);ctx.stroke();}
28
29
  if(state.style==='grid'){
@@ -35,6 +36,39 @@
35
36
  }
36
37
  ctx.globalAlpha=1;return;
37
38
  }
39
+ if(state.style==='busy'){
40
+ const n=7,bw=12,gap=11,left=cx-(n*bw+(n-1)*gap)/2;
41
+ for(let i=0;i<n;i++){
42
+ const wave=active||waiting?(Math.sin(t*(waiting?6:11)-i*.8)+1)/2:.2;
43
+ const bh=quiet?12:returned?22:14+wave*54;
44
+ ctx.globalAlpha=quiet?.15:returned?.55:.18+wave*power;ctx.fillRect(left+i*(bw+gap),cy-bh/2,bw,bh);
45
+ }
46
+ ctx.globalAlpha=1;return;
47
+ }
48
+ if(state.style==='speed'){
49
+ const span=Math.min(w-36,220),left=cx-span/2;
50
+ for(let i=0;i<7;i++){
51
+ const phase=(t*(waiting?1.5:3.3)+i*.173)%1,len=20+(i%3)*16,y=cy+(i-3)*13;
52
+ const x=active||waiting?left+phase*(span+len)-len:left+span*.43;
53
+ ctx.globalAlpha=quiet?.12:returned?.5:Math.sin(phase*Math.PI)*power;
54
+ ctx.lineWidth=i===3?3:1.5;ctx.beginPath();ctx.moveTo(Math.max(left,x),y);ctx.lineTo(Math.min(left+span,x+len),y);ctx.stroke();
55
+ }
56
+ ctx.globalAlpha=1;return;
57
+ }
58
+ if(state.style==='assembly'){
59
+ const span=Math.min(w-32,218),left=cx-span/2,rail=cy+23;
60
+ ctx.globalAlpha=quiet?.12:.26;ctx.lineWidth=1;
61
+ ctx.beginPath();ctx.moveTo(left,rail);ctx.lineTo(left+span,rail);ctx.moveTo(left,rail+8);ctx.lineTo(left+span,rail+8);ctx.stroke();
62
+ for(let i=0;i<3;i++){
63
+ const x=left+span*(i+.5)/3,phase=(t*(waiting?1.5:3.2)-i/3+9)%1,press=active||waiting?Math.max(0,1-Math.abs(phase-.5)*5):0;
64
+ ctx.globalAlpha=quiet?.16:.58;ctx.fillRect(x-14,cy-36,28,8);ctx.fillRect(x-2,cy-28,4,16+press*16);ctx.fillRect(x-9,cy-14+press*16,18,4);
65
+ }
66
+ for(let i=0;i<5;i++){
67
+ const phase=active||waiting?(t*(waiting?.7:1.6)+i/5)%1:(i+.5)/5,x=left+phase*span;
68
+ ctx.globalAlpha=quiet?.12:returned?.55:.2+Math.sin(phase*Math.PI)*power;ctx.fillRect(x-5,rail-12,10,10);
69
+ }
70
+ ctx.globalAlpha=1;return;
71
+ }
38
72
  arc(r,0,Math.PI*2,.25);arc(r*.85,0,Math.PI*2,.13);arc(r*1.12,0,Math.PI*2,.1);
39
73
  const spin=active?t*1.6:waiting?t*.9:0;
40
74
  if(state.style==='halo'){
@@ -45,17 +79,16 @@
45
79
  ctx.beginPath();ctx.moveTo(cx+Math.cos(a)*r*1.17,cy+Math.sin(a)*r*1.17);ctx.lineTo(cx+Math.cos(a)*(r*1.17+length),cy+Math.sin(a)*(r*1.17+length));ctx.stroke();
46
80
  }
47
81
  }
48
- if(state.style==='weave'||state.style==='halo'){
49
- ctx.lineWidth=.65;const strands=state.style==='weave'?62:28;
82
+ if(state.style==='halo'){
83
+ ctx.lineWidth=.65;const strands=28;
50
84
  for(let i=0;i<strands;i++){
51
- const a=i/strands*Math.PI*2+spin*.6,b=a+2.35+Math.sin(i*.68+t*1.7)*.48,inner=r*(state.style==='weave'?.84:.68);
85
+ const a=i/strands*Math.PI*2+spin*.6,b=a+2.35+Math.sin(i*.68+t*1.7)*.48,inner=r*.68;
52
86
  ctx.globalAlpha=(.1+power*.2)*(quiet?.45:1);ctx.beginPath();ctx.moveTo(cx+Math.cos(a)*inner,cy+Math.sin(a)*inner);ctx.quadraticCurveTo(cx+Math.sin(t*1.3+i)*r*.35,cy+Math.cos(i*.5+t*.7)*r*.3,cx+Math.cos(b)*inner,cy+Math.sin(b)*inner);ctx.stroke();
53
87
  }
54
88
  }
55
89
  for(let i=0;i<3;i++){
56
- const a=spin*(i%2?-1:1)+i*2.08,track=r*(state.style==='orbit'?.58+i*.25:.89+i*.06);
90
+ const a=spin*(i%2?-1:1)+i*2.08,track=r*(.89+i*.06);
57
91
  ctx.lineWidth=1.3;arc(track,a,a+(active?1.25:waiting?.75:.18),quiet?.15:.75);
58
- if(state.style==='orbit'){arc(track,0,Math.PI*2,.12);ctx.globalAlpha=quiet?.2:.8;ctx.beginPath();ctx.arc(cx+Math.cos(a)*track,cy+Math.sin(a)*track,active?2.8:2,0,Math.PI*2);ctx.fill();}
59
92
  }
60
93
  if(active||waiting){for(let i=0;i<3;i++){const q=(t*.85+i/3)%1;arc(r*(.55+q*.5),0,Math.PI*2,(1-q)*.12*power);}}
61
94
  if(returned&&!reduced){const q=Math.min((now-start)/850,1);arc(r*(1+q*.32),0,Math.PI*2,(1-q)*.5);}
@@ -64,13 +97,13 @@
64
97
 
65
98
  function animate(now) {
66
99
  raf = 0;
67
- if (!shown() || motion.matches || state.style === "off" || !["calling", "parallel", "waiting"].includes(state.scene) && !(state.scene === "returned" && now - start < 900)) return;
100
+ if (!shown() || motion.matches || state.style === "off" || !animating() && !(state.scene === "returned" && now - start < 900)) return;
68
101
  if (now - last >= 1000 / 30) { last = now;draw(now); }raf = requestAnimationFrame(animate);
69
102
  }
70
103
  function refreshAnimation() {
71
104
  cancelAnimationFrame(raf);raf = 0;root.dataset.paused = String(!shown() || motion.matches);
72
105
  if (!shown() || state.style === "off") return;
73
- draw();if (!motion.matches && (["calling", "parallel", "waiting"].includes(state.scene) || state.scene === "returned" && performance.now() - start < 900)) raf = requestAnimationFrame(animate);
106
+ draw();if (!motion.matches && (animating() || state.scene === "returned" && performance.now() - start < 900)) raf = requestAnimationFrame(animate);
74
107
  }
75
108
  function category(name) {
76
109
  const value = String(name || "").toLowerCase().split(/__|\./).at(-1);
@@ -86,34 +119,43 @@
86
119
  function render(force = false) {
87
120
  if (root.closest("[hidden]")) { signature = "";refreshAnimation();return; }
88
121
  const time = performance.now();
122
+ if (requestDeadline && time >= requestDeadline) { requests = [];requestDeadline = 0;fresh = false; }
89
123
  for (const row of records) if (row.until <= time && pending(row.state)) { row.state = "unknown";row.until = time + 300000; }
90
124
  records = records.filter(row => row.until > time);
91
125
  const rows = records.slice(0, 32).map(row => fresh || !pending(row.state) ? row : { ...row, state: "unknown" });
92
- const next = JSON.stringify([fresh, supported, state.style, omitted, rows.map(({ until, ...row }) => row)]);
126
+ const agents = fresh ? requests : [];
127
+ const next = JSON.stringify([fresh, supported, state.style, omitted, agents, rows.map(({ until, ...row }) => row)]);
93
128
  clearTimeout(expiry);expiry = null;
94
- if (records.length) expiry = setTimeout(() => render(), Math.max(1, Math.min(...records.map(row => row.until - time))));
129
+ const deadlines = records.map(row => row.until);if (requestDeadline) deadlines.push(requestDeadline);
130
+ if (deadlines.length) expiry = setTimeout(() => render(), Math.max(1, Math.min(...deadlines) - time));
95
131
  if (!force && next === signature) return;
96
132
  signature = next;
97
133
  const active = rows.filter(row => pending(row.state)), preparing = active.some(row => row.state === "preparing");
98
- const scene = active.length ? preparing ? active.length > 1 ? "parallel" : "calling" : "waiting"
134
+ const responding = agents.some(row => row.responding);
135
+ const scene = !fresh ? "idle" : active.length ? preparing ? active.length > 1 ? "parallel" : "calling" : "waiting"
136
+ : agents.length ? responding ? "responding" : "processing"
99
137
  : rows.some(row => row.state === "returned") && !rows.some(row => ["failed", "cancelled", "unknown"].includes(row.state)) ? "returned" : "idle";
100
138
  if (scene !== state.scene) start = performance.now();state.scene = scene;
101
139
  const key = !supported || !fresh ? "flow_status_unknown" : active.length ? preparing ? active.length > 1 ? "tool_preparing_many" : "tool_preparing" : "tool_waiting"
140
+ : agents.length ? agents.length > 1 ? "tool_requests_many" : responding ? "tool_responding" : "tool_processing"
102
141
  : rows.some(row => row.state === "failed") ? "tool_failed" : rows.some(row => row.state === "cancelled") ? "tool_cancelled"
103
142
  : rows.some(row => row.state === "unknown") ? "flow_status_unknown" : rows.length ? "tool_returned" : "tool_idle";
104
- text("tool-state", key, { count: active.length });
105
- canvas.setAttribute("aria-label", phrase(key, { count: active.length }));
143
+ const count = active.length || agents.length;
144
+ text("tool-state", key, { count });
145
+ canvas.setAttribute("aria-label", phrase(key, { count }));
106
146
  el("tool-style").value = state.style;el("tool-stage").dataset.style = state.style;
107
- el("tool-cursor").hidden = !active.length || state.style === "off" || !fresh;
108
- const groups = new Map(rows.map(row => [`${row.application}:${row.provider}:${row.model}`, row]));
109
- el("tool-context").hidden = !rows.length;
110
- el("tool-context").textContent = groups.size === 1 ? `${appName(rows[0].application)} · ${rows[0].model === "other" ? phrase("flow_model_pending") : rows[0].model}` : phrase("tool_groups", { count: groups.size });
147
+ el("tool-cursor").hidden = !count || state.style === "off" || !fresh;
148
+ const displayed = active.length ? rows : agents.length ? agents : rows;
149
+ const groups = new Map(displayed.map(row => [`${row.application}:${row.provider}:${row.model}`, row]));
150
+ el("tool-context").hidden = !displayed.length;
151
+ el("tool-context").textContent = groups.size === 1 ? `${appName(displayed[0].application)} · ${displayed[0].model === "other" ? phrase("flow_model_pending") : displayed[0].model}` : phrase("tool_groups", { count: groups.size });
111
152
  const list = el("tool-list");list.replaceChildren();
112
- for (const row of rows.slice(0, 6)) {
113
- const item = document.createElement("div");item.className = "tool-entry";item.dataset.state = row.state;
153
+ for (const row of displayed.slice(0, 6)) {
154
+ const agent = row.responding !== undefined;
155
+ const item = document.createElement("div");item.className = "tool-entry";item.dataset.state = agent ? "preparing" : row.state;
114
156
  const mark = document.createElement("span");mark.className = "tool-mark";mark.setAttribute("aria-hidden", "true");
115
- const name = document.createElement("span");name.className = "tool-name";name.textContent = phrase(category(row.name));
116
- const status = document.createElement("span");status.textContent = phrase(`tool_row_${row.state}`);
157
+ const name = document.createElement("span");name.className = "tool-name";name.textContent = phrase(agent ? row.responding ? "tool_response_action" : "tool_processing_action" : category(row.name));
158
+ const status = document.createElement("span");status.textContent = phrase(agent ? "tool_row_active" : `tool_row_${row.state}`);
117
159
  item.append(mark, name, status);list.append(item);
118
160
  }
119
161
  el("tool-details").hidden = !rows.length;
@@ -136,17 +178,21 @@
136
178
  new IntersectionObserver(entries => { visible = entries[0].isIntersecting;refreshAnimation(); }, { threshold: .05 }).observe(canvas);
137
179
  new MutationObserver(() => render(true)).observe(document.documentElement, { attributes: true, attributeFilter: ["lang", "data-theme", "data-palette"] });
138
180
  globalThis.ccdxToolActivity = {
139
- update(data) {
181
+ update(data, { live = false } = {}) {
140
182
  const parts = [data?.stream_performance, (data?.providers?.claude || data?.providers?.m365?.claude)?.requests?.performance].filter(Boolean);
141
183
  const views = parts.map(part => part.tool_activity).filter(value => Array.isArray(value?.items));
142
- supported = views.length > 0;fresh = supported;const time = performance.now();
184
+ supported = views.length > 0 || parts.some(part => Array.isArray(part.active_requests));fresh = supported;const time = performance.now();
185
+ requests = parts.flatMap(part => (Array.isArray(part.active_requests) ? part.active_requests.slice(0, 128) : []).filter(row => row?.purpose === "conversation" && row.terminal_outcome == null
186
+ && typeof row.model === "string" && ["received", "admission", "body", "history", "images", "serialization", "upstream_connection", "upstream_response", "upstream_stream"].includes(row.phase))
187
+ .map(row => ({ application: row.application || "api", provider: row.provider, model: row.model.slice(0, 160), responding: Number.isFinite(row.first_output_ms) && row.first_output_ms >= 0 }))).slice(0, 128);
188
+ requestDeadline = live || !requests.length ? 0 : time + 6000;
143
189
  const merged = views.flatMap((view, index) => view.items.slice(0, 32).filter(row => row && typeof row.id === "string" && ["preparing", "waiting", "returned", "failed", "cancelled", "unknown"].includes(row.state)
144
190
  && Number.isFinite(row.expires_in_ms) && row.expires_in_ms > 0).map(row => ({ id: `${index}-${row.id}`, application: row.application || "api", provider: row.provider, model: row.model || "other", name: row.name,
145
191
  state: row.state, until: time + Math.min(row.expires_in_ms, 300000) })));
146
192
  merged.sort((a, b) => Number(pending(b.state)) - Number(pending(a.state)));records = merged.slice(0, 32);
147
193
  omitted = Math.max(0, merged.length - records.length) + views.reduce((sum, view) => sum + (Number.isSafeInteger(view.omitted) ? view.omitted : 0), 0);render();
148
194
  },
149
- unavailable() { fresh = false;render(); },
195
+ unavailable() { fresh = false;requests = [];requestDeadline = 0;render(); },
150
196
  visibilityChanged() { render();refreshAnimation(); },
151
197
  };
152
198
  render();
@@ -680,7 +680,8 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
680
680
  .tool-orbit canvas { display:block;width:100%;height:100%; }
681
681
  .tool-stage[data-style="grid"] .tool-orbit { max-height:140px; }
682
682
  .tool-stage[data-style="off"] { grid-template-columns:1fr;min-height:110px; }
683
- .tool-stage[data-style="off"] .tool-visual { display:none; }
683
+ .tool-stage[data-style="off"] .tool-orbit { display:none; }
684
+ .tool-stage[data-style="off"] .tool-narration { text-align:left; }
684
685
  .tool-narration { margin:0;min-height:24px;text-align:center;color:var(--text);font-size:12px;line-height:1.7; }
685
686
  .tool-context { color:var(--muted);font-size:11px;line-height:1.6;margin:0 0 16px; }
686
687
  .tool-entry { display:grid;grid-template-columns:18px minmax(0,1fr) auto;gap:10px;align-items:center;min-height:48px;padding-block:8px;border-bottom:1px solid var(--border); }
@@ -3,6 +3,7 @@ import { sourceModels } from "./client-model-plan.mjs";
3
3
  import { isImageModel, imageModelCatalog } from "./image-models.mjs";
4
4
  import os from "node:os";
5
5
  import { publicModelCatalog } from "./provider-metadata.mjs";
6
+ import { uniqueModelEntries } from "./model-catalog.mjs";
6
7
  import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
7
8
  import { githubTokenFingerprint } from "./github-identity.mjs";
8
9
  import { validateGithubToken } from "./auth.mjs";
@@ -33,7 +34,8 @@ function endpointLabels(model) {
33
34
  }
34
35
 
35
36
  export function selectableCopilotModels(payload) {
36
- const data = Array.isArray(payload) ? payload : payload?.data;
37
+ const raw = Array.isArray(payload) ? payload : payload?.data;
38
+ const data = Array.isArray(raw) ? uniqueModelEntries(raw) : raw;
37
39
  if (!Array.isArray(data)) throw new Error("Copilot models response contained no model list");
38
40
 
39
41
  const models = [];
@@ -63,10 +65,10 @@ export function selectableCopilotModels(payload) {
63
65
  }
64
66
 
65
67
  export function publicCopilotModelCatalog(payload) {
66
- const data=Array.isArray(payload)?payload:payload.data;
68
+ const data=uniqueModelEntries(Array.isArray(payload)?payload:payload.data);
67
69
  const codex=new Set(sourceModels({id:"github",registry:{models:{data}}},"codex")
68
70
  .filter(model=>model.model_picker_enabled!==false&&(!model.policy?.state||model.policy.state==="enabled")).map(model=>model.id));
69
- const antigravity=new Set(antigravityCopilotModels(payload).map(model=>model.model));
71
+ const antigravity=new Set(antigravityCopilotModels({data}).map(model=>model.model));
70
72
  return publicModelCatalog(data,{
71
73
  selectable:model=>codex.has(model.id)||antigravity.has(model.id)||imageModelCatalog([model]).length>0,
72
74
  clients:model=>[...(codex.has(model.id)||isImageModel(model)?["codex"]:[]),...(antigravity.has(model.id)?["antigravity"]:[])],
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { readBoundedFileSync, MAX_MODEL_CACHE_FILE_BYTES } from "./bounded-file.mjs";
5
+ import { normalizeModelList } from "./model-catalog.mjs";
5
6
 
6
7
  export const MODEL_CACHE_SOFT_TTL_MS = 2 * 60 * 60 * 1000;
7
8
  export const MODEL_CACHE_HARD_TTL_MS = 7 * 24 * 60 * 60 * 1000;
@@ -50,7 +51,7 @@ export function loadModelCacheEntry({
50
51
  const ageMs = Math.max(0, now() - savedAt);
51
52
  if (ageMs > resolvedHardTtlMs) return null;
52
53
  return {
53
- models: parsed.models,
54
+ models: normalizeModelList(parsed.models),
54
55
  savedAtMs: savedAt,
55
56
  ageMs,
56
57
  state: ageMs > resolvedSoftTtlMs ? "stale" : "fresh",
@@ -74,7 +75,7 @@ export function saveModelCache(models, {
74
75
  if (typeof isCurrent === "function" && !isCurrent()) return false;
75
76
  const filePath = modelCachePath(home);
76
77
  const tempPath = `${filePath}.${process.pid}.tmp`;
77
- const payload = { saved_at: new Date(now()).toISOString(), models };
78
+ const payload = { saved_at: new Date(now()).toISOString(), models: normalizeModelList(models) };
78
79
  const fingerprint = String(credentialFingerprint || "").trim();
79
80
  if (fingerprint) payload.credential_fingerprint = fingerprint;
80
81
  fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
@@ -0,0 +1,37 @@
1
+ const record = value => value !== null && typeof value === "object" && !Array.isArray(value);
2
+
3
+ function fillMissing(first, later) {
4
+ const updates = [];
5
+ for (const [key, value] of Object.entries(later)) {
6
+ const previous = Object.hasOwn(first, key) ? first[key] : undefined;
7
+ const next = previous == null || previous === "" ? value
8
+ : record(previous) && record(value) ? fillMissing(previous, value) : previous;
9
+ if (next !== previous) updates.push([key, next]);
10
+ }
11
+ return updates.length ? { ...first, ...Object.fromEntries(updates) } : first;
12
+ }
13
+
14
+ // Call only on a single source/account catalog. Explicit values, including
15
+ // false and empty capability arrays, win; duplicates only supply missing data.
16
+ export function uniqueModelEntries(models) {
17
+ const positions = new Map();let result = null;
18
+ for (let index = 0; index < models.length; index++) {
19
+ const model = models[index], id = model?.id;
20
+ if (typeof id === "string" && id && positions.has(id)) {
21
+ result ||= models.slice(0, index);
22
+ const position = positions.get(id);
23
+ result[position] = fillMissing(result[position], model);
24
+ } else {
25
+ if (typeof id === "string" && id) positions.set(id, result ? result.length : index);
26
+ if (result) result.push(model);
27
+ }
28
+ }
29
+ return result || models;
30
+ }
31
+
32
+ export function normalizeModelList(value) {
33
+ const data = Array.isArray(value) ? value : value?.data;
34
+ if (!Array.isArray(data)) return value;
35
+ const normalized = uniqueModelEntries(data);
36
+ return normalized === data ? value : Array.isArray(value) ? normalized : { ...value, data: normalized };
37
+ }
@@ -9,6 +9,7 @@ import {
9
9
  } from "./models.mjs";
10
10
  import { initializeModelRegistry } from "./startup.mjs";
11
11
  import { status } from "./status.mjs";
12
+ import { normalizeModelList } from "./model-catalog.mjs";
12
13
 
13
14
  const DEFAULT_TIMEOUT_MS = 5000;
14
15
 
@@ -29,7 +30,7 @@ function parsedCatalog(result) {
29
30
  if (!isValidModelList(models)) {
30
31
  throw new Error("Copilot models response contained no valid models");
31
32
  }
32
- return models;
33
+ return normalizeModelList(models);
33
34
  }
34
35
 
35
36
  function createModelRegistry() {
@@ -1,6 +1,7 @@
1
1
  import { isImageModel } from "./image-models.mjs";
2
2
  import { autoReviewReasoningEfforts } from "./models.mjs";
3
3
  import { modelDisplayName } from "./model-display.mjs";
4
+ import { uniqueModelEntries } from "./model-catalog.mjs";
4
5
  // Public metadata only. Credentials and provider transport never enter this layer.
5
6
  export const isProviderId = value => typeof value === "string" && /^[a-z][a-z0-9_-]{0,63}$/.test(value)
6
7
  && !["constructor", "prototype"].includes(value);
@@ -11,7 +12,7 @@ export function modelReasoningEfforts(model) {
11
12
  }
12
13
 
13
14
  export function publicModelCatalog(models, { clients = () => [], selectable = () => false, maker = model => model.publisher || model.vendor || model.owned_by || "Unknown" } = {}) {
14
- return models.slice(0, 1000).filter(model => typeof model?.id === "string").map(model => ({
15
+ return uniqueModelEntries(models.slice(0, 1000)).filter(model => typeof model?.id === "string").map(model => ({
15
16
  id: model.id, ...(isImageModel(model) ? { kind: "image" } : {}), display_name: modelDisplayName(model), vendor: maker(model), ...(model.owned_by ? { owned_by: model.owned_by } : {}),
16
17
  endpoints: [["responses", ["/responses", "/v1/responses"]], ["chat", ["/chat/completions", "/v1/chat/completions"]],
17
18
  ["messages", ["/v1/messages"]], ["images", ["/images/generations", "/v1/images/generations"]], ["image_edits", ["/images/edits", "/v1/images/edits"]]].filter(([, paths]) => paths.some(path => model.supported_endpoints?.includes(path))).map(([label]) => label),
@@ -2,6 +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 { uniqueModelEntries } from "../model-catalog.mjs";
5
6
  import { claudeModelEntries } from "../claude-models.mjs";
6
7
  import { prepareResponsesPayload } from "../image-optimization.mjs";
7
8
  import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
@@ -190,7 +191,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
190
191
  clients: model => allowed.filter(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)) }).map(model => ({ ...model,
191
192
  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 || [])] })) }; },
192
193
  async discover({ signal } = {}) {
193
- const models = [], ids = new Set(), checked_at = new Date().toISOString();let url = modelsUrl, bytes = 0;
194
+ const models = [], cursors = new Set(), checked_at = new Date().toISOString();let url = modelsUrl, bytes = 0;
194
195
  for (let page = 0; page < 25; page++) {
195
196
  const response = await request(url, undefined, { signal }, config.endpoints.responses ? "responses" : "messages");
196
197
  if (!response.ok) {
@@ -201,14 +202,15 @@ export function createApiProvider({ config, secrets, env = process.env, platform
201
202
  const text = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES - bytes, label: "API model catalog", signal });bytes += Buffer.byteLength(text);
202
203
  let value;try { value = JSON.parse(text); } catch { throw accessError("ccdx_api_catalog_invalid", 502); }
203
204
  if (!Array.isArray(value.data) || models.length + value.data.length > 500) throw accessError("ccdx_api_catalog_invalid", 502);
204
- 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); }
205
+ 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("//")) throw accessError("ccdx_api_catalog_invalid", 502); }
205
206
  // A catalog listing is not evidence that every model supports every API.
206
- 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)
207
- ? 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]) : [] })));
208
- if (value.has_more !== true) return models;
207
+ models.push(...value.data);
208
+ if (value.has_more !== true) return uniqueModelEntries(models).map(model => ({ id: model.id, display: apiModelDisplay(model), metadata: apiModelMetadata(model, { checked_at, deployment: deploymentRevision(config, env) }), protocols: Array.isArray(model.supported_endpoints)
209
+ ? 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]) : [] }));
209
210
  // Follow only the native cursor on the configured origin, never an
210
211
  // upstream next-page URL that could disclose this source's credential.
211
- if (!value.data.length || value.last_id !== value.data.at(-1).id || bytes >= MAX_UPSTREAM_MODEL_CATALOG_BYTES) throw accessError("ccdx_api_catalog_invalid", 502);
212
+ if (!value.data.length || value.last_id !== value.data.at(-1).id || cursors.has(value.last_id) || bytes >= MAX_UPSTREAM_MODEL_CATALOG_BYTES) throw accessError("ccdx_api_catalog_invalid", 502);
213
+ cursors.add(value.last_id);
212
214
  const next = new URL(modelsUrl);next.searchParams.set("after_id", value.last_id);url = next.href;
213
215
  }
214
216
  throw accessError("ccdx_api_catalog_limit", 502);
@@ -18,6 +18,7 @@ import { limitM365CacheTtl } from "./m365-messages-policy.mjs";
18
18
  import { createM365ConversationGuard } from "./m365-conversation-accounts.mjs";
19
19
  import { catalogFailure, m365CatalogDiagnostic, m365CatalogRead } from "./m365-catalog-diagnostic.mjs";
20
20
  import { m365NetworkDiagnostic } from "./m365-network-diagnostic.mjs";
21
+ import { uniqueModelEntries } from "../model-catalog.mjs";
21
22
 
22
23
  import { M365_API_BASE, M365_API_ORIGIN } from "./m365-endpoint.mjs";
23
24
  export { M365_API_BASE } from "./m365-endpoint.mjs";
@@ -53,13 +54,13 @@ export function m365ConversationId(body, headers = {}, profile = "m365") {
53
54
 
54
55
  export function m365Catalog(payload) {
55
56
  if (!payload || !Array.isArray(payload.data) || payload.data.length > 1000) throw m365Error("m365_catalog_invalid");
56
- const seen = new Set();
57
57
  for (const model of payload.data) {
58
58
  if (!model || typeof model.id !== "string" || !/^[A-Za-z0-9][\w.-]{0,127}$/.test(model.id)
59
- || seen.has(model.id) || !Array.isArray(model.supported_endpoints)) throw m365Error("m365_catalog_invalid");
60
- seen.add(model.id);
59
+ || model.supported_endpoints != null && !Array.isArray(model.supported_endpoints)) throw m365Error("m365_catalog_invalid");
61
60
  }
62
- return { data: payload.data };
61
+ const data = uniqueModelEntries(payload.data);
62
+ if (data.some(model => !Array.isArray(model.supported_endpoints))) throw m365Error("m365_catalog_invalid");
63
+ return { data };
63
64
  }
64
65
 
65
66
  export function m365Models(catalog, family) {
@@ -89,26 +89,38 @@ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
89
89
  const messages = [];
90
90
  if (body.instructions) messages.push({ role: "system", content: body.instructions });
91
91
 
92
- const messageContent = (content) => {
93
- if (typeof content === "string") return content;
92
+ const cacheFields = value => {
93
+ if (cacheSupport?.prompt_cache_breakpoint === true) {
94
+ if (value?.prompt_cache_breakpoint != null) return { prompt_cache_breakpoint: cloneJson(value.prompt_cache_breakpoint) };
95
+ if (value?.cache_control != null) return { prompt_cache_breakpoint: { mode: "explicit" } };
96
+ }
97
+ return cacheSupport?.cache_control === true && value?.cache_control != null ? { cache_control: cloneJson(value.cache_control) } : null;
98
+ };
99
+ const messageContent = (content, owner) => {
100
+ const ownerCache = cacheFields(owner);
101
+ if (typeof content === "string") return ownerCache ? [{ type: "text", text: content, ...ownerCache }] : content;
94
102
  if (content === null) return null;
95
103
  if (!Array.isArray(content)) throw chatCompatibilityError("message content", typeof content);
96
- if (content.length === 1 && ["input_text", "output_text", "text"].includes(content[0]?.type) && typeof content[0].text === "string") return content[0].text;
104
+ if (!ownerCache && content.length === 1 && ["input_text", "output_text", "text"].includes(content[0]?.type) && typeof content[0].text === "string" && !cacheFields(content[0])) return content[0].text;
97
105
  const parts = [];
98
106
  for (const part of content) {
99
107
  if (!part || typeof part !== "object") throw chatCompatibilityError("message content", part?.type);
100
108
  if (["input_text", "output_text", "text"].includes(part.type)) {
101
109
  if (typeof part.text !== "string") throw chatCompatibilityError("message content", part.type);
102
- parts.push({ type: "text", text: part.text });
110
+ parts.push({ type: "text", text: part.text, ...cacheFields(part) });
103
111
  } else if (["input_image", "image_url", "image"].includes(part.type)) {
104
112
  const imagePart = chatImagePart(part);
105
- if (imagePart) parts.push(imagePart);
113
+ if (imagePart) parts.push({ ...imagePart, ...cacheFields(part) });
106
114
  else throw chatCompatibilityError("message content", part.type);
107
115
  } else {
108
116
  throw chatCompatibilityError("message content", part.type);
109
117
  }
110
118
  }
111
- if (parts.length === 1 && parts[0].type === "text") return parts[0].text;
119
+ if (ownerCache) {
120
+ if (!parts.length) parts.push({ type: "text", text: "" });
121
+ const last = parts.length - 1;parts[last] = { ...ownerCache, ...parts[last] };
122
+ }
123
+ if (parts.length === 1 && parts[0].type === "text" && !Object.hasOwn(parts[0], "cache_control") && !Object.hasOwn(parts[0], "prompt_cache_breakpoint")) return parts[0].text;
112
124
  return parts;
113
125
  };
114
126
 
@@ -121,9 +133,9 @@ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
121
133
  && ["user", "assistant", "system", "developer"].includes(item?.role)
122
134
  && Object.prototype.hasOwnProperty.call(item, "content");
123
135
  if (item?.type === "message" || isEasyMessage) {
124
- messages.push({ role: item.role, content: messageContent(item.content) });
136
+ messages.push({ role: item.role, content: messageContent(item.content, item) });
125
137
  } else if (item?.type === "agent_message") {
126
- if (typeof item.author !== "string" || typeof item.recipient !== "string" || !Array.isArray(item.content)) {
138
+ if (typeof item.author !== "string" || typeof item.recipient !== "string" || !Array.isArray(item.content) || item.encrypted_content != null) {
127
139
  throw chatCompatibilityError("input item", "agent_message");
128
140
  }
129
141
  const escape = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
@@ -193,6 +205,9 @@ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
193
205
  if (cacheSupport.prompt_cache_retention === true && ["in_memory", "24h"].includes(body.prompt_cache_retention)) {
194
206
  chatReq.prompt_cache_retention = body.prompt_cache_retention;
195
207
  }
208
+ if (cacheSupport.prompt_cache_options === true && body.prompt_cache_options && typeof body.prompt_cache_options === "object" && !Array.isArray(body.prompt_cache_options)) {
209
+ chatReq.prompt_cache_options = cloneJson(body.prompt_cache_options);
210
+ }
196
211
  }
197
212
  const maxTok = body.max_output_tokens ?? body.max_tokens ?? body.max_completion_tokens;
198
213
  if (maxTok !== undefined) chatReq.max_completion_tokens = maxTok;
@@ -128,6 +128,9 @@ function stripEncryptedReasoningValue(value, state) {
128
128
  }
129
129
 
130
130
  function stripEncryptedReasoningInputValue(item, state) {
131
+ // A sealed agent message may contain the entire delegated task. Removing
132
+ // opaque parts would turn a rejected task into an unrelated plaintext ask.
133
+ if (item?.type === "agent_message") return item;
131
134
  if (!isResponsesToolOutputItem(item)) {
132
135
  const out = stripEncryptedReasoningValue(item, state);
133
136
  if (item?.type === "message"