codex-copilot-dx 0.10.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +18 -17
  2. package/bin/cli.mjs +24 -3
  3. package/docs/ARCHITECTURE.md +60 -14
  4. package/docs/README.md +3 -0
  5. package/docs/REFERENCE.md +186 -45
  6. package/package.json +2 -2
  7. package/src/adapter.mjs +19 -4
  8. package/src/browser-launch.mjs +22 -0
  9. package/src/claude-client-config.mjs +22 -5
  10. package/src/claude-gateway.mjs +30 -8
  11. package/src/claude-models.mjs +26 -0
  12. package/src/cli-animation.mjs +1 -1
  13. package/src/cli-image.mjs +3 -0
  14. package/src/cli-m365.mjs +1 -1
  15. package/src/cli-options.mjs +11 -6
  16. package/src/cli-table.mjs +1 -1
  17. package/src/client-integration.mjs +5 -1
  18. package/src/dashboard/console.js +141 -0
  19. package/src/dashboard/index.html +105 -52
  20. package/src/dashboard/language.js +103 -0
  21. package/src/dashboard/refresh.js +2 -1
  22. package/src/dashboard/status.js +60 -29
  23. package/src/dashboard/ui.css +49 -0
  24. package/src/dashboard/ui.js +113 -26
  25. package/src/dashboard-api.mjs +72 -7
  26. package/src/dashboard.mjs +1 -0
  27. package/src/image-mcp.mjs +9 -6
  28. package/src/live-models.mjs +11 -3
  29. package/src/log.mjs +13 -11
  30. package/src/m365-settings.mjs +0 -2
  31. package/src/native-prediction-recovery.mjs +1 -0
  32. package/src/native-prediction.mjs +6 -2
  33. package/src/observability.mjs +8 -1
  34. package/src/optional-routes.mjs +2 -2
  35. package/src/provider-metadata.mjs +21 -0
  36. package/src/provider-runtime.mjs +80 -26
  37. package/src/providers/m365-auth.mjs +4 -4
  38. package/src/providers/m365.mjs +10 -2
  39. package/src/response-failures.mjs +1 -1
  40. package/src/service-control.mjs +60 -0
  41. package/src/startup-ui.mjs +4 -3
  42. package/src/terminal-console.mjs +87 -0
  43. package/src/usage-analysis.mjs +1 -1
  44. package/src/usage-analytics.mjs +3 -3
  45. package/src/usage-store.mjs +40 -17
  46. package/src/usage.mjs +14 -7
  47. package/src/user-settings.mjs +21 -0
package/docs/REFERENCE.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # CCDX command, configuration and compatibility reference
2
2
 
3
3
  Use Codex App with GPT models available to your **GitHub Copilot** account by default.
4
- The optional [Microsoft 365 provider](#microsoft-365-provider) supplies a separate
4
+ The optional [Microsoft 365 provider](#microsoft-365-provider) supplies a protocol-isolated
5
5
  Claude gateway and an explicitly selected Codex backup.
6
6
 
7
7
  ## Microsoft 365 provider
@@ -70,15 +70,17 @@ Codex source and M365 review choices live separately in
70
70
  GitHub auth/cache/preferences, Codex auth, prediction trust and image keys are not
71
71
  copied into the M365 profile. The system's Microsoft SSO account is never deleted.
72
72
 
73
- M365 catalogs refresh at startup and on the existing background model interval.
74
- Request-time catalog reads use the account-bound cache, trigger refresh after two
75
- hours and reject disk caches older than seven days. `ccdx models`, Auto-review's
76
- selector and dashboard models follow the selected Codex source. Under M365 they
77
- use the running provider's catalog, labeled as a catalog rather than a fresh
78
- per-command GitHub lookup. Disabled/hidden models and wrong publisher/protocol
79
- families are not exposed. A catalog listing is not proof that inference will pass
80
- quota or policy checks. M365 Fast is unverified and `priority` requests fail
81
- explicitly; choose Standard. This does not change GitHub Fast behavior.
73
+ M365 catalogs refresh at startup and on explicit lookups. Existing model-list
74
+ reads and Claude Messages traffic start a background refresh after two hours;
75
+ disk caches older than seven days are rejected. `ccdx models` and Auto-review's
76
+ selector follow the selected Codex source. Dashboard tabs query a registered
77
+ Provider independently of that selection; M365 uses a fresh provider catalog
78
+ lookup and labels the returned catalog timestamp. Its disabled/hidden or
79
+ ineligible models remain visible as directory metadata, with no eligible client.
80
+ Client discovery and request validation still exclude wrong publishers/protocols
81
+ and disabled/hidden models. A listing does not prove inference access or quota.
82
+ M365 Fast is unverified and `priority` requests fail explicitly; choose Standard.
83
+ GitHub Fast behavior is unchanged.
82
84
 
83
85
  M365 Auto-review has its own required model choice and defaults to low reasoning.
84
86
  `ccdx auto-review-model` changes that provider's model/effort without touching the
@@ -88,18 +90,29 @@ optional image MCP/skill/API remains separately configured and off by default.
88
90
 
89
91
  ### Claude gateway and client ownership
90
92
 
91
- The gateway is a second listener in the same Node service, on `127.0.0.1:2027`.
92
- If the core service itself is configured on 2027, CCDX reserves that port for the
93
- core and skips only the Claude listener/setup. M365 GPT backup still works. Select
94
- a different core `ADAPTER_PORT` if both client surfaces are needed; no port is moved automatically.
95
- It accepts a private local Bearer key or `x-api-key`, rejects browser Origin
96
- headers and exposes Claude only: `GET /v1/models`, `POST /v1/messages` and
97
- `POST /v1/messages/count_tokens` (upstream support remains authoritative).
98
- Messages tools, thinking, cache breakpoints, image blocks, beta headers and native
99
- SSE are relayed without OpenAI-format conversion. Cancellation and downstream
100
- backpressure are preserved. Upstream and local gateway credentials are distinct;
101
- the local key is never forwarded upstream. The legacy Claude URL on port 2026
102
- remains retired. Claude requests never reach GitHub.
93
+ Since 1.1.0, Claude mounts under the main HTTP listener at
94
+ `http://127.0.0.1:<ADAPTER_PORT>/anthropic` (default main port 2026).
95
+ It exposes `GET /anthropic/v1/models`, `POST /anthropic/v1/messages` and
96
+ `POST /anthropic/v1/messages/count_tokens`. The Claude Base URL excludes the final `/v1`.
97
+ The local socket, loopback Host, native-client Origin rejection and private Bearer
98
+ or `x-api-key` checks remain independent of any main-listener LAN opt-in.
99
+ Messages tools, thinking, signatures, image blocks, beta headers and SSE retain
100
+ their native protocol and backpressure/cancellation handling. Provider-specific
101
+ cache policy is described below; the local gateway key is never forwarded upstream.
102
+
103
+ The protocol handler owns only its responses, never the shared server. Codex,
104
+ WebUI and Claude share the main port; native prediction keeps its CONNECT/PAC
105
+ transport and saved port. Root `/v1/messages` remains retired, including on a
106
+ custom main port. Claude requests never reach GitHub. M365 GPT-only catalogs do
107
+ not configure Claude. Optional Claude setup failure leaves the Codex backup independent.
108
+
109
+ Unchanged CCDX-owned Code/App addresses migrate from 2027 to the shared prefix,
110
+ with the original restoration values preserved. User-edited fields, managed
111
+ settings and explicit environment routes remain preserved. CCDX does not keep
112
+ a permanent 2027 compatibility listener; migrate hand-written old URLs explicitly.
113
+ Already-running clients may need a normal restart to reload their base URL.
114
+ Disabling/removing M365 is rejected while its Codex or Claude inference is active,
115
+ so an accepted disable does not cut off those requests.
103
116
 
104
117
  Loki explicitly rejects one-hour prompt-cache retention. M365's request policy
105
118
  caps standard `cache_control: {type: "ephemeral", ttl: "1h"}` fields to `5m`,
@@ -108,6 +121,33 @@ breakpoint positions, tool input, thinking and approval settings do not change.
108
121
  This is a retention/cost limitation of the new M365 path, not an equivalent
109
122
  one-hour cache guarantee. GitHub caching is unchanged.
110
123
 
124
+ The gateway publishes canonical Claude version IDs such as `claude-opus-5-5`,
125
+ while M365 receives its exact `claude-opus-5.5` ID. Existing raw IDs are still
126
+ accepted. Only exact supported family/version spellings are normalized; alias
127
+ collisions fail explicitly. Bodies, thinking signatures and native response bytes
128
+ remain intact apart from the existing cache-TTL policy and the upstream model ID.
129
+
130
+ `capabilities.supports.reasoning_effort` supplies deployment-specific effort
131
+ metadata. App `inferenceModels` entries receive the highest recognized advertised
132
+ `maxEffort`; Code discovery receives canonical IDs. A successful catalog refresh
133
+ reconciles unchanged owned fields outside inference serialization. An owned legacy
134
+ Code default can migrate to its matching canonical ID; valid user model/effort
135
+ preferences are preserved. Reads after a profile change invalidate page catalogs.
136
+ Unknown metadata stays unknown. Unknown effort names remain visible as upstream
137
+ metadata and are not invented as App caps. When an explicit effort list exists,
138
+ requests for absent efforts fail before inference, without dropping the field or
139
+ substituting a lower level. Missing metadata leaves the upstream authoritative.
140
+
141
+ App effort controls also depend on its model knowledge. Supported versions can
142
+ read Anthropic's signed catalog under the App's existing network and management
143
+ policy; CCDX neither replaces that signed document nor changes its URL/policy.
144
+ `maxEffort` is a ceiling, not an arbitrary discrete allowlist: client-visible
145
+ options may differ from an upstream's sparse list, while exact request validation
146
+ remains authoritative. Unknown model identities or new protocol semantics can
147
+ still need a client or CCDX update. A displayed control alone is not an inference
148
+ verification. See [Claude model configuration](https://claude.com/docs/third-party/claude-desktop/configuration)
149
+ and [gateway behavior](https://code.claude.com/docs/en/llm-gateway-protocol).
150
+
111
151
  For Claude Code, CCDX owns only its gateway environment fields in
112
152
  `CLAUDE_CONFIG_DIR/settings.json` or `~/.claude/settings.json`. For Claude App it
113
153
  uses the installed client's third-party config library, with one named
@@ -669,8 +709,8 @@ Credentials found are not labeled online-authorized, cached model lists are not
669
709
  labeled fresh upstream data, and image configuration is not a provider test.
670
710
  Ready reports core readiness independently of optional prediction/image warnings.
671
711
  Model refresh logs show counts; `ccdx models` retains the complete live list.
672
- After Ready, background refresh uses the same two-column status/message layout as
673
- other runtime logs. Status messages remove terminal controls and collapse newlines;
712
+ After Ready, the default foreground display becomes a fixed status region;
713
+ request and background-refresh detail is available with `--verbose` or explicit file logging. Status messages remove terminal controls and collapse newlines;
674
714
  the static banner and multiline interactive prompts retain their own presentation.
675
715
  VS Code compatibility-version details remain available in debug logging. Startup
676
716
  does not wait for optional update/compression work or add online doctor/model probes.
@@ -728,6 +768,65 @@ ccdx limits --decoded default
728
768
 
729
769
  `ccdx limits` distinguishes the saved decoded request-body limit from the running adapter's active limit. The default is 128 MiB; the opt-in saved limit accepts 128–512 MiB. Changes take effect only after restarting the adapter, never restart it automatically, and do not clear conversations or caches. `CCDX_MAX_DECODED_BODY_BYTES` overrides the saved setting; unset it before changing the saved limit. The separate 64 MiB raw/compressed-body limit is not changed. Larger decoded requests can use substantially more process memory during JSON parsing and image preparation; raising this limit may enable a large thread to compact, but does not guarantee successful inference or compaction. Return to `default` after temporary use.
730
770
 
771
+ ### Control console and online settings
772
+
773
+ The sidebar separates Overview, Codex/Claude clients, Model services, Usage and
774
+ diagnostics, and System/settings. Codex owns optional image generation, native
775
+ prediction adaptation and the temporary Responses conversation buffer. That
776
+ buffer supports continuation; it is not a chat archive. Shared HTTP traffic and
777
+ per-protocol model outcomes are distinct. Claude Messages metrics are not labeled
778
+ as all Microsoft 365 traffic. Saved credentials, authorization, catalog discovery,
779
+ client configuration and successful requests are separate evidence.
780
+
781
+ Interactive desktop starts open the default browser once after core readiness.
782
+ `--no-browser` skips this for one invocation; `open_webui:false` in
783
+ `~/.config/codex-copilot-dx/config.json` disables subsequent automatic opening.
784
+ Query commands do not open it. Headless/CI/SSH or noninteractive starts skip it;
785
+ a browser-launch failure does not stop the service. This is an opening attempt,
786
+ not a guarantee that every browser will reuse an existing tab.
787
+
788
+ The default TTY display uses four bounded lines, without an alternate screen or
789
+ raw keyboard input. It shows usage returned since this process began; pending
790
+ usage is excluded, missing usage stays partial, and this is not an invoice.
791
+ Business requests drive activity; status/catalog polling does not. Existing nine
792
+ animation themes retain their timing/palette and cycle pauses. `--verbose`,
793
+ `--show-request-id` or `CCDX_LOG_LEVEL=debug` restore detailed terminal output.
794
+ Non-TTY/CI/dumb/very narrow terminals use plain output; repeated identical notices
795
+ are coalesced. File logging retains its existing explicit opt-in and redaction.
796
+ In-memory usage still updates when `CCDX_DISABLE_USAGE=1` disables persistence.
797
+
798
+ The settings API is local, requires the dashboard header, bounded JSON and
799
+ same-origin POST. It invokes the same Provider, cache and integration operations;
800
+ it does not spawn a CLI or generic shell command. Settings reads do not reveal
801
+ upstream keys. Each operation reads back saved and effective state. Corrupt saved
802
+ service preferences fail closed for optional calls rather than reopening them.
803
+
804
+ | Control | Effective scope |
805
+ | --- | --- |
806
+ | Terminal theme/animation | Live supported status terminal; plain/verbose/environment-disabled modes are reported separately |
807
+ | Open WebUI | Next interactive desktop start |
808
+ | Image calls | New local MCP calls; keeps provider credentials and allows an already-started call to finish |
809
+ | Prediction adaptation | Subsequent configuration traffic on an already-provisioned bridge; keeps trust/route, and App caches can remain |
810
+ | Model source | Explicit validated selection for subsequent Codex requests; existing requests retain their binding |
811
+ | Conversation buffer | Live validated limit; cleanup refuses pinned/active data and can invalidate old unused continuation IDs |
812
+
813
+ Boolean allow preferences `terminal_animation_enabled`, `image_enabled` and
814
+ `prediction_enabled` default to true, preserving already configured features;
815
+ they do not provision or enable the default-off image/prediction integrations.
816
+ The existing explicit CLI enable commands resume the corresponding paused gate.
817
+ `disable-image` and `prediction off` retain their documented full cleanup
818
+ semantics, distinct from a WebUI pause. First-time setup and client trust/routing
819
+ changes still use existing compatibility checks and may require a normal App
820
+ relaunch. Environment-controlled limits cannot be overridden through the page.
821
+
822
+ Visible auto-refresh reads the in-memory status approximately every two seconds,
823
+ and Provider/settings evidence approximately every 16 seconds. Hidden pages stop
824
+ scheduled reads. Catalogs and retained usage are fetched only for their open view
825
+ or an explicit lookup; their normal refresh interval remains 30 minutes. Paused
826
+ auto-refresh still permits manual refresh/settings retry. No history-log scan is
827
+ performed at the status cadence. The atom moves on load/manual refresh only and
828
+ respects reduced motion. Client attribution absent from older records stays unknown.
829
+
731
830
  ### Terminal animation
732
831
 
733
832
  Choose the terminal activity animation interactively:
@@ -752,7 +851,7 @@ All nine rows preview their animations together while you enter a number to sele
752
851
 
753
852
  All nine animations use the same 20-column colon track and cyan/blue palette. They indicate activity, not completion percentage. Braille was removed in 0.7.7. A saved `terminal_animation: "braille"` falls back to Comet without rewriting the settings file; choosing another animation replaces it, and explicitly choosing Comet clears it. Other settings remain intact.
754
853
 
755
- The selected theme is loaded once when a new adapter starts, so changing it does not restart or alter an adapter that is already running. Stop and start CCDX to apply the new theme. `CCDX_TERMINAL_ANIMATION=0` (also `false`, `no`, or `off`) remains the boolean gate that disables terminal animation regardless of the selected theme.
854
+ Running 1.1.0+ services pick up a changed saved theme without restarting. The WebUI applies it directly; the CLI gallery save is picked up by the status renderer within about one second. Older services still need a restart after upgrade. `CCDX_TERMINAL_ANIMATION=0` (also `false`, `no`, or `off`) remains the boolean gate that disables terminal animation regardless of the selected theme.
756
855
 
757
856
  ### Optional image generation
758
857
 
@@ -993,23 +1092,65 @@ JSON reply to a streaming request is still not silently converted to SSE.
993
1092
 
994
1093
  ### Local dashboard
995
1094
 
996
- After starting `ccdx`, open [http://127.0.0.1:2026/](http://127.0.0.1:2026/) in a browser. If `ADAPTER_PORT` is customized, use that port instead. The dashboard shares the existing adapter listener; CCDX does not open a browser automatically or start another service. The page and its assets require both a loopback connection and a loopback Host header, even when LAN binding is enabled.
997
-
998
- The dashboard loads local status, a live GitHub Copilot model directory, and a summary of local usage metadata once when opened. The top Refresh updates status/account and expanded data groups; model and usage sections retain their own Refresh controls. Auto refresh is on by default, saved only in this browser, and updates status/account plus expanded groups every 30 minutes while the page is visible. Opening a data section updates its group unless it was attempted within 30 seconds. Hidden pages pause; returning after 30 minutes catches up once, without replaying missed intervals. Turning automatic updates off retains manual and open-section refresh. No server background task is added. In-flight reads are shared per group; failures retain the prior snapshot and success timestamp. Unchanged model rows and charts are retained rather than rebuilt. The appearance button switches between the default dark terminal theme (sun icon) and a light theme (moon icon); the choice is stored only in that browser. The Requests card shows the running adapter's active raw and decoded per-request body limits, not request-body usage; Local History shows its in-memory Responses history use and active limit. Limit changes remain CLI-only (`ccdx limits` and `ccdx cache`). The live model table uses the same fresh account validation and selectable GPT filtering as `ccdx models`, never labels cached fallback data as online, and makes no inference request. A catalog listing does not guarantee inference access. The Model Usage table combines the current and rotated local usage logs, shows totals and up to 100 model rows, and contains no prompt, response body, or credential fields. The animation selector previews the existing themes and saves through the same settings writer as `ccdx animation`; changes take effect on the next adapter start, and `CCDX_TERMINAL_ANIMATION=off` still disables terminal motion. Dashboard data requests require a custom header that cross-site simple requests cannot send; animation writes also require a matching same-origin `Origin`. The dashboard does not initialize the optional image handler. The overview's known-model count is the adapter's current in-memory catalog, not the live table. A missing image-generation status does not prove the feature is disabled: use `ccdx image-status` to check setup. Recent upstream error prose may contain sensitive details, so review the page before sharing screenshots.
999
-
1000
- The dashboard labels the upstream token cache hit metric **Reuse Rate** and cached input **Reused Input**, separate from **Local History**. Chinese uses short functional names such as “对话暂存”, “重用输入” and “重用比例”. English and Chinese preserve model IDs, commands, units, HTTP status codes and raw diagnostic values. Animation display names translate in place; theme IDs and CLI parameters do not change.
1001
-
1002
- The transparent, single-color atom-orbit favicon follows the dashboard's saved light/dark choice without a separate network request.
1003
-
1004
- The saved GitHub Copilot account appears immediately to the left of the Status updated time. It uses the same local credentials and fingerprint-bound identity metadata as `ccdx auth status`, with username (or numeric ID fallback) and a `SAVED` label; this is not an online entitlement check. Missing, invalid, unidentified, or unreadable credentials are shown explicitly. The account read runs on page load, top Refresh and visible-page automatic updates, independently of adapter status and without upstream authentication calls. Its timestamp is in the account tooltip; failed updates retain the prior account and explicitly label the failure. Its loopback-only, custom-header-protected API exposes no token, fingerprint, credential path, or raw metadata. The general status endpoint retains its existing identity-free contract.
1005
-
1006
- Account names containing underscores are supported, including `dingxiao_microsoft`. A numeric ID is a fallback, not a replacement for an available, safely displayable username; the existing length bounds and credential-shaped text suppression still apply.
1007
-
1008
- The language button immediately right of the appearance button switches between English and Simplified Chinese. English remains the default; the choice is saved only in the current browser, separately from light/dark mode. Switching translates the existing page in place: it does not fetch API data, rebuild charts, change selected filters, discard unsaved animation choices, or reset expanded failure details. Static labels, live status text, chart tooltips and accessibility labels follow the selected language. Model IDs, account names, dates, numeric values and upstream diagnostic prose stay unchanged; copied diagnostic fields retain their original names and values. The local translation asset adds no dependency, external service, polling or inference-path work.
1009
-
1010
- Usage Trends is collapsed by default. Opening it adds daily input/output token bars (7/30/90 days) and a 365-day calendar of recorded usage calls or tokens, grouped in the browser's time zone. Cache-read tokens are already part of input and are not added again. Model and range filters use the current snapshot without additional requests; selecting a day shows its filtered model totals in the Model Usage table, and Show all restores the original table. Analytics shares the existing current/rotated-log scan and exposes only bounded metadata (365 days, up to 100 model filters). Days before retained history are hatched, not presented as zero; the oldest retained day may be partial. Counts describe retained usage records, not messages, session time, or all HTTP requests. Open-section, manual and visible-page automatic refresh update the snapshot. Analytics are requested only while expanded inside the open usage section or while a day filter needs them. Filters and selected dates survive refresh; a closed unfiltered chart reuses its displayed data until reopened. There is no server background collection.
1011
-
1012
- Terminal Animation is collapsed at the bottom of the page, with an Animation shortcut in the header. Preview frames load only when opened; closing it, hiding the page, or requesting reduced motion stops the preview timer. Unsaved choices survive folding and reopening. Recent response failures expand to diagnostic fields (time, model, code, message, response/request IDs, and retry policy) with a Copy details control. The view combines the last 10 retained `response.failed` events with failures from the 20 most recently finished Responses/compact requests, showing at most 10 entries. Matching local request IDs attach the final outcome and timing metadata, so a recovered event can show `completed`; an uncorrelated retry attempt does not prove recovery. Transport failures and incomplete/cancelled requests can appear without a `response.failed` event. These are bounded runtime observations, not complete session histories. Diagnostic prose is redacted by the existing recorder but can still contain sensitive context: review before copying or sharing.
1095
+ Interactive desktop starts open [http://127.0.0.1:2026/](http://127.0.0.1:2026/)
1096
+ once by default, using the configured main port when customized. See
1097
+ [control console and online settings](#control-console-and-online-settings) for
1098
+ startup preferences, output modes and effective-state rules. Assets require both
1099
+ a loopback connection and loopback Host, including when the main listener uses LAN mode.
1100
+
1101
+ The sidebar separates Overview, Codex/Claude clients, Model services, Usage and
1102
+ diagnostics, and System/settings. Codex-specific images, prediction integration
1103
+ and conversation buffering stay under Codex. HTTP traffic counts include model
1104
+ catalogs and route errors; model outcomes and timing are named by protocol.
1105
+ Microsoft 365's Claude Messages summary is not a Provider-wide request total.
1106
+
1107
+ The account table uses bounded local credential metadata and Provider snapshots.
1108
+ A locally saved GitHub credential is not online entitlement. Account names with
1109
+ underscores retain their exact display value; identity, keys and environment
1110
+ values are not inferred from model names. Client configuration, gateway state,
1111
+ recent requests and actual inference are separate observations. The top summary
1112
+ shows selected client-to-Provider routes; it is not an account label.
1113
+
1114
+ Catalog tabs browse registered Provider directories without changing routing.
1115
+ Rows retain protocol, eligible clients, reasoning metadata and directory state.
1116
+ Unknown metadata stays unknown; listings are not verified inference access.
1117
+ A separate explicit source form validates and applies subsequent Codex routing.
1118
+ Existing active streams keep their Provider binding. User/organization client
1119
+ configuration is not overwritten by browsing or by a pause operation.
1120
+
1121
+ Top Refresh updates local evidence and open data groups, plus current-page settings.
1122
+ Auto-refresh defaults on and is browser-local. Small status snapshots update about
1123
+ every two seconds; source/settings evidence updates every eight status ticks.
1124
+ Catalogs and retained usage load only on demand or in their open view, with the
1125
+ existing 30-minute cadence and short freshness gate. Hidden pages stop scheduled
1126
+ reads. Catalog requests are deduplicated, stale tab reads are cancelled and late
1127
+ results rejected. Failed reads preserve last-good data and label it as stale.
1128
+ Service-setting errors are visible on the current page and can be retried manually.
1129
+
1130
+ The usage selector retains current and historical sources. Combined model rows
1131
+ and daily analytics preserve source identity; old records without a client label
1132
+ are not guessed into one. Legacy untagged Provider records retain their historical
1133
+ GitHub attribution. Cache-read tokens are included in input, not added twice.
1134
+ The separate current-run summary updates from returned usage in memory, without
1135
+ rescanning retained logs at the status cadence.
1136
+
1137
+ Usage analytics remains collapsed until opened: 7/30/90-day bars and a bounded
1138
+ 365-day calendar in the browser time zone. Model/range/day selection reuses its
1139
+ snapshot. Days outside retained history are distinct from zero recorded activity.
1140
+ Filters, chart nodes and unsaved animation selection survive unrelated refreshes.
1141
+ Dark/light, English/Chinese and reduced motion remain supported. Language changes
1142
+ translate page labels in place without fetching models or rebuilding charts;
1143
+ commands, identifiers and upstream error text retain their original values.
1144
+
1145
+ Terminal appearance lives in System/settings, with a sidebar shortcut on wide
1146
+ screens. Preview frames load on opening; closing, hiding the view/page or reduced
1147
+ motion stops preview timers. Saving changes the running supported status terminal.
1148
+
1149
+ The recent-failure view merges bounded Responses events, main-listener HTTP
1150
+ failures and recent Responses/compact/Messages request timelines, with at most ten
1151
+ visible entries. Request IDs correlate final outcomes; a retry alone is not proof
1152
+ of recovery. It is diagnostic metadata, not a session archive. Original error
1153
+ responses remain unchanged. Review upstream diagnostic prose before sharing.
1013
1154
 
1014
1155
  Inspect only the local Codex configuration:
1015
1156
 
@@ -1195,11 +1336,11 @@ unset the variable after the investigation. Records disappear on service exit.
1195
1336
  | `CCDX_UPSTREAM_RETRIES` | `2` | Retries for safe requests and clearly pre-connect POST failures; capped at `5` |
1196
1337
  | `CCDX_UPSTREAM_RETRY_DELAY_MS` | `300` | Initial upstream retry backoff in milliseconds; capped at `5000` |
1197
1338
  | `CCDX_AUTO_REVIEW_MODEL` | saved selection or `gpt-6.1-sol` | Copilot Responses model used for Codex Auto-review; overrides the interactive selection |
1198
- | `CCDX_LOG_PATH` | unset | Mirror terminal logs to a file; set to `1` for `~/.local/share/codex-copilot-dx/debug.log` |
1339
+ | `CCDX_LOG_PATH` | unset | Record diagnostic logs independently of quiet terminal presentation; set to `1` for `~/.local/share/codex-copilot-dx/debug.log` |
1199
1340
  | `CCDX_LOG_LEVEL` | `info` | Set to `debug` for upstream attempts, status codes, retry causes, and timings |
1200
1341
  | `CCDX_HTTP_ERROR_DETAILS` | unset | Set to `1` on a new service to retain redacted HTTP error excerpts (500 characters) in bounded memory; review before sharing, no file logging is enabled |
1201
1342
  | `CCDX_LOG_MAX_BYTES` | `16777216` | Rotate the debug log at this size and retain one `.1` backup; set to `0` to disable rotation |
1202
- | `CCDX_TERMINAL_ANIMATION` | auto | Show the selected transient animation while an interactive terminal has active requests and no output for 800 ms; set to `0`, `false`, `no`, or `off` to disable |
1343
+ | `CCDX_TERMINAL_ANIMATION` | auto | Allow the selected animation in the fixed interactive status region during business activity; set to `0`, `false`, `no`, or `off` to disable |
1203
1344
  | `CCDX_IMG_MAX_DIM` | `2048` | Maximum long edge in pixels for image downscaling |
1204
1345
  | `CCDX_IMG_QUALITY` | `82` | Initial WebP quality for image re-encoding |
1205
1346
  | `CCDX_IMG_MIN_BYTES` | `100000` | In-bounds images smaller than this skip re-encoding; oversized dimensions still trigger an optimization attempt |
@@ -1243,7 +1384,7 @@ Diagnostic redaction removes Basic authorization payloads and URL userinfo, and
1243
1384
 
1244
1385
  ## Debug logging
1245
1386
 
1246
- Set `CCDX_LOG_PATH=1` to mirror terminal logs to `~/.local/share/codex-copilot-dx/debug.log`, or provide a custom path. Add `CCDX_LOG_LEVEL=debug` for upstream attempts, retry causes, status codes, and timings. The adapter does not deliberately dump request/response bodies or authorization headers. File diagnostics redact common credential forms and labelled content echoes, but this cannot identify every secret in arbitrary external prose; review logs before sharing them. File writes are asynchronous and batched with a 4096-record / 2 MiB pending-and-in-flight ceiling. Overflow drops excess file records with one warning and a status counter; terminal output continues. CLI exit paths flush for at most 1.5 seconds. `ccdx doctor config` bypasses file logging entirely.
1387
+ Set `CCDX_LOG_PATH=1` to record diagnostic logs independently of quiet terminal presentation to `~/.local/share/codex-copilot-dx/debug.log`, or provide a custom path. Add `CCDX_LOG_LEVEL=debug` for upstream attempts, retry causes, status codes, and timings. The adapter does not deliberately dump request/response bodies or authorization headers. File diagnostics redact common credential forms and labelled content echoes, but this cannot identify every secret in arbitrary external prose; review logs before sharing them. File writes are asynchronous and batched with a 4096-record / 2 MiB pending-and-in-flight ceiling. Overflow drops excess file records with one warning and a status counter; terminal output continues. CLI exit paths flush for at most 1.5 seconds. `ccdx doctor config` bypasses file logging entirely.
1247
1388
 
1248
1389
  ## Large histories and images
1249
1390
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "0.10.1",
4
- "description": "Use Codex App with GitHub Copilot",
3
+ "version": "1.1.0",
4
+ "description": "Local Codex adapter and optional Microsoft 365 Claude gateway",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
7
7
  "bin": {
package/src/adapter.mjs CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  import { httpError } from "./http-errors.mjs";
29
29
  import { createRequestAdmission } from "./request-admission.mjs";
30
30
  import { PROVIDER_MANAGEMENT_PATH, handleProviderManagement } from "./provider-management.mjs";
31
+ import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
31
32
 
32
33
  export {
33
34
  abortErrorStatusCode,
@@ -167,10 +168,12 @@ export function createAdapterHandler(options = {}) {
167
168
  const responseFailures = options.responseFailures || createResponseFailureDiagnostics();
168
169
  const httpErrors = createHttpFailureDiagnostics();
169
170
  const optionalRoutes = createOptionalRoutes({ ...options, dashboardOptions: { ...options.dashboardOptions,
170
- ...(options.providerRuntime ? { providerCatalogFn: () => options.providerRuntime.dashboardCatalog() } : {}) } });
171
+ ...(options.providerRuntime ? { providerCatalogFn: input => options.providerRuntime.dashboardCatalog(input),
172
+ providerStateFn: () => options.providerRuntime.dashboardProviders() } : {}) } });
173
+ let statusSnapshot;
171
174
  const managementHandler = createManagementHandler({
172
175
  nativePredictionPac: options.nativePredictionPac, fixPrediction: options.fixPrediction, requestBodyTimeoutMs,
173
- statusSnapshot: () => {
176
+ statusSnapshot: statusSnapshot = () => {
174
177
  const snapshot = runtimeStatusPayload({ metrics: requestMetrics, streamPerformance: streamPerformanceMetrics, admission: acquireRequest,
175
178
  imagePressure, responseFailures, imageGeneration: optionalRoutes.imageStats(),
176
179
  modelRegistry: codexModelRegistry, codexClient, codexModelRegistry, codexModelCatalog,
@@ -238,6 +241,16 @@ export function createAdapterHandler(options = {}) {
238
241
  return providerHandlers.get(provider);
239
242
  }
240
243
  const dispatch = async (req, res, pathname) => {
244
+ if (pathname.startsWith("/anthropic/")) {
245
+ if (!isLoopbackAddress(req.socket?.remoteAddress) || !req.headers?.host || !isLoopbackHostHeader(req.headers.host)
246
+ || Object.hasOwn(req.headers, "origin")) { sendJsonError(res, httpError("Claude requires native local clients", 403));return; }
247
+ if (!options.providerRuntime?.handleClaude) { sendJsonError(res, httpError("Claude is not configured", 503));return; }
248
+ const original = req.url;
249
+ const query = new URL(req.url, "http://localhost").search;
250
+ req.url = pathname.slice("/anthropic".length) + query;
251
+ try { return await options.providerRuntime.handleClaude(req, res); }
252
+ finally { req.url = original; }
253
+ }
241
254
  if (req.method === "POST" && ["/v1/responses", "/v1/responses/compact"].includes(pathname)
242
255
  && Object.hasOwn(req.headers || {}, "origin")) {
243
256
  const error = httpError("Browser origins are not allowed for inference", 403);
@@ -367,7 +380,7 @@ export function createAdapterHandler(options = {}) {
367
380
  const complete = trackRequest ? requestMetrics.begin(routeName) : () => {};
368
381
  const streamPerformance = trackRequest ? streamPerformanceMetrics.begin(routeName, { requestId }) : null;
369
382
  let finishTerminalActivity = () => {};
370
- if (trackRequest) {
383
+ if (trackRequest && ["responses", "responses_compact", "messages", "image_mcp"].includes(routeName)) {
371
384
  try {
372
385
  const finish = options.terminalActivity?.beginRequest?.();
373
386
  if (typeof finish === "function") finishTerminalActivity = finish;
@@ -381,7 +394,7 @@ export function createAdapterHandler(options = {}) {
381
394
  if (trackRequest && statusCode >= 400) {
382
395
  try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model,
383
396
  method: ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"].includes(req.method) ? req.method : "OTHER",
384
- target: ["/v1/responses", "/v1/responses/compact", "/mcp/image", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname) ? pathname : "unrecognized_path",
397
+ target: ["/v1/responses", "/v1/responses/compact", "/anthropic/v1/messages", "/anthropic/v1/messages/count_tokens", "/anthropic/v1/models", "/mcp/image", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname) ? pathname : "unrecognized_path",
385
398
  request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.(),
386
399
  attempt_timings: streamPerformance?.attemptTimings?.(),
387
400
  requested_model: context?.requestedModel, provider: context?.provider,
@@ -444,6 +457,7 @@ export function createAdapterHandler(options = {}) {
444
457
  containUnexpectedError(error);
445
458
  }
446
459
  };
460
+ handler.snapshot = statusSnapshot;
447
461
  return handler;
448
462
  }
449
463
 
@@ -456,6 +470,7 @@ export function startAdapter(port = 2026, host = "127.0.0.1", options = {}) {
456
470
  : options.terminalActivity;
457
471
  const handler = createAdapterHandler({ ...options, terminalActivity, imageMcpHostname: host });
458
472
  const server = http.createServer(handler);
473
+ server.ccdxSnapshot = handler.snapshot;
459
474
  const cleanupTerminalActivity = () => {
460
475
  if (ownsTerminalActivity) terminalActivity?.cleanup?.();
461
476
  handler.cleanup?.();
@@ -0,0 +1,22 @@
1
+ import { spawn } from "node:child_process";
2
+ import path from "node:path";
3
+
4
+ export async function openDashboard(baseUrl, { env = process.env, platform = process.platform, spawnImpl = spawn,
5
+ interactive = process.stdout.isTTY === true, enabled = true, timeoutMs = 3000 } = {}) {
6
+ const url = new URL(baseUrl);
7
+ if (url.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)
8
+ || url.username || url.password || url.search || url.hash) throw new Error("Dashboard launch requires a local HTTP URL");
9
+ if (!enabled || !interactive || env.CI && !/^(0|false|no|off)$/i.test(env.CI) || env.SSH_CONNECTION || env.SSH_TTY
10
+ || platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY) return { opened: false, state: "skipped" };
11
+ const command = platform === "darwin" ? "open" : platform === "win32"
12
+ ? path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "rundll32.exe") : "xdg-open";
13
+ const args = platform === "win32" ? ["url.dll,FileProtocolHandler", url.href] : [url.href];
14
+ return new Promise(resolve => {
15
+ let child, timer;
16
+ const finish = opened => { clearTimeout(timer);resolve({ opened, state: opened ? "opened" : "unavailable" }); };
17
+ try { child = spawnImpl(command, args, { stdio: "ignore", windowsHide: true }); }
18
+ catch { finish(false);return; }
19
+ child.once("error", () => finish(false));child.once("exit", code => finish(code === 0));
20
+ timer = setTimeout(() => { child.unref?.();finish(false); }, timeoutMs);timer.unref?.();
21
+ });
22
+ }
@@ -8,6 +8,7 @@ import { readBoundedFileSync } from "./bounded-file.mjs";
8
8
  import { atomicWriteFileSync } from "./atomic-file.mjs";
9
9
  import { withFileLockSync } from "./lock.mjs";
10
10
  import { m365Paths, readM365Json, writeM365Json } from "./m365-settings.mjs";
11
+ import { claudeClientModelId, claudeModelEntries } from "./claude-models.mjs";
11
12
 
12
13
  export const M365_CLAUDE_PROFILE_ID = "00000000-0000-4000-8000-000000202700";
13
14
  const M365_CLAUDE_PROFILE_NAME = "CCDX Microsoft 365";
@@ -152,9 +153,13 @@ function reconcile(operations, { restore = false, ...options } = {}) {
152
153
  }
153
154
 
154
155
  export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, ...options } = {}) {
155
- const paths = claudeClientPaths(options), ids = models.map(model => model.id), operations = [], result = {};
156
+ const entries = claudeModelEntries(models);
157
+ const paths = claudeClientPaths(options), ids = entries.map(model => model.name), operations = [], result = {};
156
158
  const endpoint = new URL(baseUrl);
157
- if (endpoint.protocol !== "http:" || endpoint.hostname !== "127.0.0.1" || endpoint.pathname !== "/" || endpoint.search || endpoint.hash || endpoint.username || endpoint.password) throw new Error("Claude gateway must use a local root URL");
159
+ if (endpoint.protocol !== "http:" || endpoint.hostname !== "127.0.0.1" || !["/", "/anthropic"].includes(endpoint.pathname) || endpoint.search || endpoint.hash || endpoint.username || endpoint.password) throw new Error("Claude gateway must use a local root or /anthropic URL");
160
+ const journal = readM365Json(m365Paths(options).ownership, { version: 1, operations: [] });
161
+ const owns = (file, keys, value) => journal.version === 1 && Array.isArray(journal.operations)
162
+ && journal.operations.some(op => op.file === file && isDeepStrictEqual(op.keys, keys) && isDeepStrictEqual(op.after, value));
158
163
  const add = (file, keys, value, itemId) => operations.push({ file, keys, value, ...(itemId ? { itemId } : {}) });
159
164
  const env = options.env || process.env;
160
165
  let code;
@@ -168,14 +173,18 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
168
173
  || code?.apiKeyHelper
169
174
  || ["CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "CLAUDE_CODE_USE_ANTHROPIC_AWS", "CLAUDE_CODE_USE_GATEWAY"].some(key => /^(1|true)$/i.test(env[key] || codeEnv[key] || ""));
170
175
  if (!code) { /* Keep independent App setup available when Code settings are damaged. */ }
171
- else if (envConflict || codeEnv.ANTHROPIC_BASE_URL && codeEnv.ANTHROPIC_BASE_URL !== baseUrl) result.code = "preserved";
176
+ else if (envConflict || codeEnv.ANTHROPIC_BASE_URL && codeEnv.ANTHROPIC_BASE_URL !== baseUrl
177
+ && !owns(paths.code, ["env", "ANTHROPIC_BASE_URL"], codeEnv.ANTHROPIC_BASE_URL)) result.code = "preserved";
172
178
  else {
173
179
  add(paths.code, ["env", "ANTHROPIC_BASE_URL"], baseUrl);
174
180
  add(paths.code, ["env", "ANTHROPIC_AUTH_TOKEN"], apiKey);
175
181
  add(paths.code, ["env", "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"], "1");
176
182
  if (env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS === undefined) add(paths.code, ["env", "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"], "1");
177
183
  add(paths.code, ["env", "ANTHROPIC_CUSTOM_HEADERS"], "X-CCDX-Client: claude-code");
178
- if (!codeEnv.ANTHROPIC_MODEL && ids.length) add(paths.code, ["env", "ANTHROPIC_MODEL"], ids[0]);
184
+ if (ids.length && (!codeEnv.ANTHROPIC_MODEL || models.some(model => model.id === codeEnv.ANTHROPIC_MODEL))) {
185
+ const index = models.findIndex(model => model.id === codeEnv.ANTHROPIC_MODEL);
186
+ add(paths.code, ["env", "ANTHROPIC_MODEL"], ids[Math.max(0, index)]);
187
+ }
179
188
  result.code = "configured";
180
189
  }
181
190
  const installed = desktopInstalled ?? (fs.existsSync(path.dirname(paths.normal)) || fs.existsSync(path.dirname(paths.threep))
@@ -189,13 +198,21 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
189
198
  else if (meta.hybridPointer || meta.appliedId && meta.appliedId !== M365_CLAUDE_PROFILE_ID
190
199
  || profile.inferenceProvider && profile.inferenceProvider !== "gateway"
191
200
  || profile.inferenceGatewayBaseUrl && profile.inferenceGatewayBaseUrl !== baseUrl
201
+ && !owns(paths.profile, ["inferenceGatewayBaseUrl"], profile.inferenceGatewayBaseUrl)
192
202
  || profile.inferenceGatewayApiKey && profile.inferenceGatewayApiKey !== apiKey) result.app = "preserved";
193
203
  else {
194
204
  add(paths.profile, ["inferenceProvider"], "gateway");
195
205
  add(paths.profile, ["inferenceGatewayBaseUrl"], baseUrl);
196
206
  add(paths.profile, ["inferenceGatewayApiKey"], apiKey);
197
207
  add(paths.profile, ["inferenceGatewayAuthScheme"], "bearer");
198
- add(paths.profile, ["inferenceModels"], JSON.stringify(ids));
208
+ let previousModels = [];
209
+ try { previousModels = JSON.parse(profile.inferenceModels || "[]"); } catch { /* Ownership reconciliation preserves a user-modified field. */ }
210
+ const order = new Map((Array.isArray(previousModels) ? previousModels : []).map((entry, index) => {
211
+ const name = typeof entry === "string" ? entry : entry?.name;
212
+ return [typeof name === "string" ? claudeClientModelId(name) : "", index];
213
+ }));
214
+ const orderedEntries = [...entries].sort((left, right) => (order.get(left.name) ?? Infinity) - (order.get(right.name) ?? Infinity));
215
+ add(paths.profile, ["inferenceModels"], JSON.stringify(orderedEntries));
199
216
  add(paths.profile, ["inferenceCustomHeaders"], JSON.stringify({ "X-CCDX-Client": "claude-app" }));
200
217
  add(paths.meta, ["entries"], { id: M365_CLAUDE_PROFILE_ID, name: M365_CLAUDE_PROFILE_NAME }, M365_CLAUDE_PROFILE_ID);
201
218
  add(paths.meta, ["appliedId"], M365_CLAUDE_PROFILE_ID);
@@ -1,3 +1,5 @@
1
+ import { isProviderId } from "./provider-metadata.mjs";
2
+ import { claudeModelEntries } from "./claude-models.mjs";
1
3
  import http from "node:http";
2
4
  import { randomUUID, timingSafeEqual } from "node:crypto";
3
5
  import { createRequestAbort, readJsonBody, readBoundedResponseText, writeOrDrain, MAX_UPSTREAM_ERROR_BODY_BYTES } from "./http-transport.mjs";
@@ -5,7 +7,7 @@ import { createRequestAdmission } from "./request-admission.mjs";
5
7
  import { loadRuntimeConfig } from "./runtime-config.mjs";
6
8
  import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
7
9
  import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
8
- import { runWithRequestContext } from "./request-context.mjs";
10
+ import { runWithRequestContext, currentRequestContext } from "./request-context.mjs";
9
11
  import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
10
12
  import { buildMessagesUsageRecord, recordUsage } from "./usage-store.mjs";
11
13
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
@@ -55,7 +57,7 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024) {
55
57
 
56
58
  export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, onRequest = () => {}, env = process.env,
57
59
  record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
58
- if (!provider || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
60
+ if (!provider || !isProviderId(provider.id) || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
59
61
  const config = loadRuntimeConfig(env), performance = createStreamPerformanceMetrics({ routeNames: ["messages"] });
60
62
  const decodedLimit = decodedBodyLimitPreference({ env }).bytes;
61
63
  const stats = { total: 0, active: 0, completed: 0, incomplete: 0, failed: 0, cancelled: 0, last_request_at: null, last_model: null };
@@ -65,19 +67,25 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
65
67
  if (!authenticated(req.headers, apiKey)) { send(res, 401, apiError("ccdx_gateway_auth", "Invalid local gateway credential"));return; }
66
68
  let pathname;try { pathname = new URL(req.url, "http://localhost").pathname; } catch { send(res, 400, apiError("ccdx_invalid_path", "Invalid request path"));return; }
67
69
  if (req.method === "GET" && pathname === "/v1/models") {
68
- const models = provider.models("claude").map(model => ({ id: model.id, type: "model", display_name: typeof model.name === "string" && model.name || model.id }));
69
- send(res, 200, { data: models, has_more: false, first_id: models[0]?.id || null, last_id: models.at(-1)?.id || null });return;
70
+ try {
71
+ const entries = provider.models("claude");
72
+ const models = claudeModelEntries(entries).map((entry, index) => ({ id: entry.name, type: "model", display_name: typeof entries[index].name === "string" && entries[index].name || entry.name }));
73
+ send(res, 200, { data: models, has_more: false, first_id: models[0]?.id || null, last_id: models.at(-1)?.id || null });
74
+ } catch (error) { send(res, 503, apiError(error.code || "ccdx_catalog_unavailable", "Claude model discovery is unavailable; refresh the provider catalog.")); }
75
+ return;
70
76
  }
71
77
  if (!["/v1/messages", "/v1/messages/count_tokens"].includes(pathname)) { send(res, 404, apiError("ccdx_not_found", "Not found"));return; }
72
78
  if (req.method !== "POST") { send(res, 405, apiError("ccdx_method", "Use POST"));return; }
73
79
  if (!/^application\/json(?:\s*;|$)/i.test(req.headers["content-type"] || "")) { send(res, 415, apiError("ccdx_media_type", "Expected application/json"));return; }
74
- const countTokens = pathname.endsWith("/count_tokens"), requestId = randomUUID();
80
+ const parent = currentRequestContext();
81
+ if (parent) parent.provider = provider.id;
82
+ const countTokens = pathname.endsWith("/count_tokens"), requestId = parent?.requestId || randomUUID();
75
83
  const tracker = countTokens ? null : performance.begin("messages", { requestId });
76
- tracker?.setProvider("m365");
84
+ tracker?.setProvider(provider.id);
77
85
  const abort = createRequestAbort(req, res);
78
86
  let release = () => {}, outcome = "failed", model = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
79
87
  if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
80
- await runWithRequestContext({ requestId, provider: "m365", route: "messages", streamPerformance: tracker }, async () => {
88
+ await runWithRequestContext({ requestId, provider: provider.id, route: "messages", streamPerformance: tracker }, async () => {
81
89
  try {
82
90
  release = await acquireRequest(req, { signal: abort.signal });
83
91
  abort.setTimeout(config.requestBodyTimeoutMs, "request_body_timeout");
@@ -143,7 +151,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
143
151
  tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : "upstream_response", reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
144
152
  tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: res.statusCode });
145
153
  const client = req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude";
146
- try { void Promise.resolve(record(buildMessagesUsageRecord({ model, responseId, usage, mode: streamed ? "stream" : "json", client }))).catch(() => {}); } catch {}
154
+ try { void Promise.resolve(record(buildMessagesUsageRecord({ model, responseId, usage, mode: streamed ? "stream" : "json", client, provider: provider.id }))).catch(() => {}); } catch {}
147
155
  }
148
156
  }
149
157
  });
@@ -153,6 +161,20 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
153
161
  return handler;
154
162
  }
155
163
 
164
+ // Mounted by the main dispatcher. Own only Claude responses, never the shared listener.
165
+ export function createClaudeGateway(options = {}) {
166
+ const handler = createClaudeGatewayHandler(options), responses = new Set();
167
+ let closed = false;
168
+ return { port: options.port, snapshot: handler.snapshot,
169
+ handle(req, res) {
170
+ if (closed) { send(res, 503, apiError("ccdx_gateway_closed", "Claude is stopping"));return; }
171
+ responses.add(res);
172
+ return Promise.resolve(handler(req, res)).finally(() => responses.delete(res));
173
+ },
174
+ async close() { closed = true;for (const res of responses) res.destroy?.();responses.clear(); },
175
+ };
176
+ }
177
+
156
178
  export async function startClaudeGateway(options = {}) {
157
179
  const handler = createClaudeGatewayHandler(options), server = http.createServer(handler);
158
180
  server.headersTimeout = 15000;server.requestTimeout = 120000;
@@ -0,0 +1,26 @@
1
+ import { modelReasoningEfforts } from "./provider-metadata.mjs";
2
+
3
+ const EFFORTS = ["low", "medium", "high", "xhigh", "max"];
4
+
5
+ // M365's version separator differs from Anthropic's model ID spelling. Other
6
+ // aliases and unknown families are kept verbatim, never assigned another model.
7
+ export function claudeClientModelId(id) {
8
+ return id.replace(/^(claude-(?:opus|sonnet|haiku)-\d+)\.(\d+)$/, "$1-$2");
9
+ }
10
+
11
+ export function claudeModelEntries(models) {
12
+ const ids = new Set();
13
+ return models.map(model => {
14
+ const name = claudeClientModelId(model.id);
15
+ if (ids.has(name)) throw Object.assign(new Error("Claude model aliases collide; refresh the provider catalog"), { code: "claude_model_alias_collision", statusCode: 503 });
16
+ ids.add(name);
17
+ const advertised = modelReasoningEfforts(model);
18
+ const maxEffort = EFFORTS.filter(value => advertised?.includes(value)).at(-1);
19
+ return { name, ...(maxEffort ? { maxEffort } : {}) };
20
+ });
21
+ }
22
+
23
+ export function resolveClaudeModel(models, id) {
24
+ claudeModelEntries(models); // Refuse ambiguous catalogs, including exact-ID collisions.
25
+ return models.find(model => model.id === id || claudeClientModelId(model.id) === id);
26
+ }