codex-copilot-dx 1.2.15 → 1.2.17
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 +6 -6
- package/docs/ARCHITECTURE.md +49 -5
- package/docs/REFERENCE.md +99 -11
- package/package.json +1 -1
- package/src/access-settings.mjs +22 -4
- package/src/adapter.mjs +11 -2
- package/src/claude-capability-config.mjs +89 -0
- package/src/claude-client-config.mjs +20 -10
- package/src/claude-gateway.mjs +71 -26
- package/src/claude-models.mjs +21 -9
- package/src/client-model-plan.mjs +75 -0
- package/src/connection-runtime.mjs +176 -41
- package/src/dashboard/connections.js +137 -51
- package/src/dashboard/index.html +51 -49
- package/src/dashboard/language.js +60 -2
- package/src/dashboard/ui.css +16 -0
- package/src/model-capabilities.mjs +91 -0
- package/src/providers/api.mjs +17 -15
- package/src/responses-handler.mjs +22 -0
- package/src/stream-performance.mjs +4 -1
package/README.md
CHANGED
|
@@ -11,13 +11,13 @@ npm install -g codex-copilot-dx@latest
|
|
|
11
11
|
ccdx
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.
|
|
14
|
+
No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.17/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.17/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
|
|
15
15
|
|
|
16
16
|
CCDX reuses a compatible local credential or starts GitHub Device Flow, listens on `127.0.0.1:2026`, configures Codex, and opens the App. Interactive desktop starts also open the local WebUI once; use `ccdx --no-browser` or disable this in WebUI settings. No client binary patch is needed. On Windows, open the App manually unless native prediction setup is enabled. In restricted Windows PowerShell, use `npm.cmd` to install and `ccdx.cmd` for the first launch, or run `ccdx.cmd doctor --fix`. Startup, updates and explicit repair remove only CCDX's exact npm-generated `.ps1` launchers so later calls can use `ccdx`. The npm package adds no install hook or policy change; custom launchers are preserved. npm's own script is untouched. The configured `dummy` API key is a placeholder, not a credential.
|
|
17
17
|
|
|
18
|
-
The [local control console](http://127.0.0.1:2026/) separates Overview, Codex/Claude, Model sources, Usage, Requests, Checks & repairs and Settings, with a stable sticky header.
|
|
18
|
+
The [local control console](http://127.0.0.1:2026/) separates Overview, Codex/Claude, Model sources, Usage, Requests, Checks & repairs and Settings, with a stable sticky header. Model sources owns API accounts, keys and model capabilities; application pages own visible models and defaults. Settings owns independent web/terminal colors (classic green, Klein blue or Soft pink), startup and updates. Accounts and model catalogs stay with Model sources; client-specific tools stay with their application. CLI remains English; WebUI supports English/Chinese. An interactive terminal shows bounded startup checks, source/client state, a usage table with approximate cache hit rate, notices and animation. Plain/NO_COLOR/narrow output remains supported; `--verbose` retains request detail.
|
|
19
19
|
|
|
20
|
-
Requests shows live app/source/model flow above existing summaries and finished records. Usage offers animated bars or curves; reduced motion stays static. Hidden pages stop scheduled reads; status refreshes about every two seconds and source/settings evidence about every 16 seconds. Catalogs and retained usage load on demand or every 30 minutes while open. The UI does not add inference calls. Ready means local service availability, not verified model access. First output uses ms, speed token/s, and partial/unknown usage remains explicit. Images/predictions stay opt-in; their first setup uses CLI. See the [control reference](docs/REFERENCE.md#control-console-and-online-settings), [1.2.
|
|
20
|
+
Requests shows live app/source/model flow above existing summaries and finished records. Usage offers animated bars or curves; reduced motion stays static. Hidden pages stop scheduled reads; status refreshes about every two seconds and source/settings evidence about every 16 seconds. Catalogs and retained usage load on demand or every 30 minutes while open. The UI does not add inference calls. Ready means local service availability, not verified model access. First output uses ms, speed token/s, and partial/unknown usage remains explicit. Images/predictions stay opt-in; their first setup uses CLI. See the [control reference](docs/REFERENCE.md#control-console-and-online-settings), [1.2.17 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.17.md) and [copy inventory](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/UX_COPY.md).
|
|
21
21
|
|
|
22
22
|
## Commands
|
|
23
23
|
| Command | Purpose |
|
|
@@ -52,11 +52,11 @@ Requests shows live app/source/model flow above existing summaries and finished
|
|
|
52
52
|
|
|
53
53
|
## Add your own API
|
|
54
54
|
|
|
55
|
-
Run `ccdx web` without GitHub sign-in. In **
|
|
55
|
+
Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. A request stays on its selected deployment; there is no automatic cross-source retry or model replacement. Reopen clients after configuration changes and start a new conversation after source/key changes. Stop management before normal `ccdx` startup for the live terminal.
|
|
56
56
|
|
|
57
|
-
Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving
|
|
57
|
+
Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving makes no upstream call. Closed sources can be restored on Model sources; closed apps remain reachable for restoration on their app pages. Pinned streams finish on their original source. The version-two graph preserves old single-source visibility and saves a byte-for-byte v1 backup before migration. User and managed client settings remain protected.
|
|
58
58
|
|
|
59
|
-
|
|
59
|
+
Model details distinguish API declarations, manual values and unknown fields. Context, maximum input/output, reasoning levels, input types, tools and protocol-specific native search are deployment-specific; missing metadata is not inferred from names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization).
|
|
60
60
|
|
|
61
61
|
## Microsoft 365 access
|
|
62
62
|
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -20,11 +20,41 @@ Client integration, image tools and the dashboard are not a general plugin frame
|
|
|
20
20
|
### Manual connection graph (1.2.13)
|
|
21
21
|
|
|
22
22
|
`provider-runtime.mjs` composes built-in lifecycle with `connection-runtime.mjs`,
|
|
23
|
-
which owns grants, switches
|
|
23
|
+
which owns grants, switches, versioned model-deployment bindings and lifecycle. `access-settings.mjs`
|
|
24
24
|
validates strict versioned metadata and locked atomic writes; stale cross-process
|
|
25
25
|
saves are rejected. Accepted inputs and public snapshots do not share mutable
|
|
26
26
|
objects with the live graph. The built-in registry does not load external code.
|
|
27
27
|
|
|
28
|
+
`model-capabilities.mjs` owns neutral limits, reasoning/tool/input/search fields,
|
|
29
|
+
strict manual values, per-field evidence and deployment revisions. It reads no
|
|
30
|
+
credentials or client files. Explicit manual values override the current API's
|
|
31
|
+
structured declarations; absent or generation-mismatched fields remain unknown.
|
|
32
|
+
`client-model-plan.mjs` compiles immutable authorized catalogs, source-qualified
|
|
33
|
+
routes and client metadata. Same-named models never collapse into one deployment.
|
|
34
|
+
Legacy null bindings retain their original single-source catalog; explicit arrays
|
|
35
|
+
expose only selected models. A v1 file is backed up byte-for-byte before the first
|
|
36
|
+
atomic v2 write. Source grants are not silently promoted to model grants.
|
|
37
|
+
|
|
38
|
+
Compiled plans are cached by immutable binding/source/catalog identities and
|
|
39
|
+
generation, not serialized on each request. The control plane refreshes metadata;
|
|
40
|
+
the data plane resolves a model once after its admitted bounded body read, then
|
|
41
|
+
pins the real provider, history namespace and capability snapshot through the
|
|
42
|
+
stream. Responses and Messages keep their existing admission, cancellation,
|
|
43
|
+
backpressure and history paths. A shared Messages admission pool spans client
|
|
44
|
+
handlers. Failed calls do not select another provider.
|
|
45
|
+
|
|
46
|
+
`claude-capability-config.mjs` plans shared App Code/Code host fields once for all
|
|
47
|
+
managed consumers, then uses `claude-client-config.mjs`'s existing field journal.
|
|
48
|
+
Per-model compact budgets are distinct from the largest shared host window.
|
|
49
|
+
Unknown/unsupported consumers prevent unsafe global context overrides; unowned
|
|
50
|
+
Code base settings, explicit environment values and manual fields are preserved.
|
|
51
|
+
Shared operations have a separate restore selector, so pausing Code cannot tear
|
|
52
|
+
down active App budgets. Sync work coalesces and reruns once for newer control
|
|
53
|
+
state rather than letting concurrent App/Code writes race. No permission or
|
|
54
|
+
safety-review field is owned by this adapter. Native version/schema limitations
|
|
55
|
+
are public data, not fabricated capabilities. Output constraints are recorded as
|
|
56
|
+
bounded revision/constraint labels in existing request context observations.
|
|
57
|
+
|
|
28
58
|
`providers/api.mjs` owns configured native clients, model capabilities,
|
|
29
59
|
configuration/key history identity and explicit bounded discovery. It uses no
|
|
30
60
|
Copilot/M365 retry or request-body policy. Its lazy transport is retained per
|
|
@@ -44,9 +74,7 @@ addresses, credentials, headers or prompts.
|
|
|
44
74
|
|
|
45
75
|
The API editor separates catalog candidates from selected models. Only selected
|
|
46
76
|
models enter the strict saved graph, with a required native protocol; unused
|
|
47
|
-
ID-only catalog entries cannot invalidate a save. Client grants remain separate
|
|
48
|
-
from route availability: manual sources need configured models for the client's
|
|
49
|
-
protocol before they are offered as its current source.
|
|
77
|
+
ID-only catalog entries cannot invalidate a save. Client grants remain separate from model visibility and protocol reachability. Source CRUD/capability details live on Model sources; application pages select deployments/defaults and review synchronization; Settings retains common preferences. The App and Code use separate segments and keys.
|
|
50
78
|
|
|
51
79
|
`api-secrets.mjs` owns OS-protected credentials and a private-pipe cache; no
|
|
52
80
|
command argument contains an upstream key. Failed metadata commits remove their
|
|
@@ -62,6 +90,20 @@ independent app/code lifecycles. M365 beta policy is not imposed on API clients;
|
|
|
62
90
|
adding a source alone never migrates old client credentials. Configuring clients
|
|
63
91
|
does not patch/restart their binaries or override managed settings.
|
|
64
92
|
|
|
93
|
+
`claude-models.mjs` owns deterministic desktop compatibility routes for manual
|
|
94
|
+
Messages sources. The same mapping feeds the App field writer, authenticated
|
|
95
|
+
App catalog and gateway resolver; Code/Codex and M365 do not adopt these aliases.
|
|
96
|
+
Standard Claude IDs retain their native family identity. Other model routes use
|
|
97
|
+
opaque digits with the real ID as `labelOverride`, without asserting Anthropic
|
|
98
|
+
capabilities. The gateway canonicalizes the request before history validation
|
|
99
|
+
and upstream dispatch, then projects the requested alias only into the returned
|
|
100
|
+
JSON model field or SSE message-start model field. Bounded SSE observation
|
|
101
|
+
retains other frames and applies client backpressure without a separate tee.
|
|
102
|
+
Usage and performance continue to identify the upstream model. A route cannot
|
|
103
|
+
authorize a model outside its source's Messages catalog.
|
|
104
|
+
For this same manual App boundary, system-role text is collected into the native
|
|
105
|
+
top-level system field in order; conversation blocks and their order are retained.
|
|
106
|
+
|
|
65
107
|
`conversation-source-guard.mjs` retains bounded HMAC correlations for observed
|
|
66
108
|
managed histories. Known source/key conflicts fail before forwarding. It does
|
|
67
109
|
not establish provenance for an unseen history or implement dynamic affinity.
|
|
@@ -70,6 +112,8 @@ The existing Responses route-plan boundary continues to own opaque-state checks.
|
|
|
70
112
|
`dashboard/connections.js` owns settings forms; application source/review and
|
|
71
113
|
account/catalog views keep their existing scopes and use the same backend graph.
|
|
72
114
|
Full configuration is on-demand; ordinary status uses compact cached summaries.
|
|
115
|
+
Disabled sources and clients have separate restore lists inside their owning
|
|
116
|
+
Settings cards, hidden when empty.
|
|
73
117
|
Shared Messages observation includes all sources, while M365-specific status
|
|
74
118
|
projects M365 counts. Bounds cover two built-ins plus 16 APIs without unbounded
|
|
75
119
|
labels, request histories, body logging or a new refresh loop.
|
|
@@ -82,7 +126,7 @@ its Fast mapping, retries and recovery are not applied blindly to M365. Protocol
|
|
|
82
126
|
adaptation belongs to the client boundary. There is no generic intermediate message
|
|
83
127
|
format that would erase native Responses or Anthropic semantics.
|
|
84
128
|
|
|
85
|
-
`provider-registry.mjs` declares the bounded internal source metadata used by selection validation and dashboard source choices. It loads no external code; GitHub and M365 remain built-in sources. `access-settings.mjs` validates up to 16 user-defined API records; `providers/api.mjs` is their first-party implementation, not a third-party code loader. Client grants
|
|
129
|
+
`provider-registry.mjs` declares the bounded internal source metadata used by selection validation and dashboard source choices. It loads no external code; GitHub and M365 remain built-in sources. `access-settings.mjs` validates up to 16 user-defined API records; `providers/api.mjs` is their first-party implementation, not a third-party code loader. Client grants, selected deployment sets and defaults remain in composition.
|
|
86
130
|
|
|
87
131
|
`provider-runtime.mjs` owns source selection, not the providers themselves. Each
|
|
88
132
|
request pins a provider before admission. An explicit change affects later requests;
|
package/docs/REFERENCE.md
CHANGED
|
@@ -7,10 +7,10 @@ Claude gateway and an explicitly selected Codex backup.
|
|
|
7
7
|
## Manual APIs and client access
|
|
8
8
|
|
|
9
9
|
`ccdx web` starts management without GitHub sign-in or automatic App launch.
|
|
10
|
-
Use **
|
|
10
|
+
Use **Model sources → Add API**, save the HTTPS API base address/key
|
|
11
11
|
(including a required prefix such as `/v1`), then reopen **Manage → Read models**.
|
|
12
12
|
Select the models to use and their supported interfaces, save, then choose each
|
|
13
|
-
client's
|
|
13
|
+
client's visible models and default on **Codex** or **Claude**. Unselected catalog entries
|
|
14
14
|
are not saved. A selected model needs at least one interface; choosing an
|
|
15
15
|
interface also selects its model. Manual ID entry is an optional collapsed path
|
|
16
16
|
for models absent from the catalog. Only Codex on GitHub needs the default
|
|
@@ -48,14 +48,35 @@ or inference call. **Read models** performs one explicit catalog read, with a
|
|
|
48
48
|
support until reviewed. Opening normal views reads saved models rather than
|
|
49
49
|
probing every API. `ccdx models` labels manual models as configured, not live.
|
|
50
50
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
or
|
|
51
|
+
For manual Messages APIs, CCDX writes Claude App's model configuration
|
|
52
|
+
automatically. Standard Claude IDs keep their existing identity; other IDs use
|
|
53
|
+
a stable `ccdx/claude-compatible-<digits>` route with `labelOverride` set to the
|
|
54
|
+
real model ID. Reordering or adding models does not renumber existing routes.
|
|
55
|
+
The App's model catalog advertises the same routes and real display names.
|
|
56
|
+
Users do not need to add aliases manually. Owned configuration migrates through
|
|
57
|
+
the existing field journal; custom or managed settings remain protected.
|
|
58
|
+
|
|
59
|
+
Only the authenticated Claude App binding enables this translation. The gateway
|
|
60
|
+
resolves routes against that source's allowed Messages models, sends real IDs
|
|
61
|
+
upstream for Messages and token counting, and returns the requested route in
|
|
62
|
+
JSON messages or SSE `message_start.message.model`. Other SSE frames, tool data
|
|
63
|
+
and signatures are retained. Alias SSE framing is bounded by the existing event
|
|
64
|
+
limit and follows client backpressure. Usage and request diagnostics keep real
|
|
65
|
+
model IDs. Explicit multi-source bindings use source-qualified routes for Codex and both Claude clients. Unqualified legacy IDs resolve only when exactly one authorized deployment matches. Source/key history boundaries and native protocol semantics remain enforced.
|
|
66
|
+
|
|
67
|
+
Some App requests include `system` messages as well as a top-level `system`
|
|
68
|
+
field, including system notes after user content. For manual App connections,
|
|
69
|
+
CCDX appends their text blocks to the top-level field in system-message order,
|
|
70
|
+
retaining system priority, block metadata and the order/content of conversation
|
|
71
|
+
messages. Non-text system content fails locally. Other clients and providers
|
|
72
|
+
keep their existing payload paths.
|
|
73
|
+
|
|
74
|
+
Compatibility routes address Claude App's model-name filter. A saved connection,
|
|
75
|
+
successful model-list read or connection check does not prove complete App
|
|
76
|
+
conversation, tool or thinking support for every upstream model.
|
|
55
77
|
|
|
56
78
|
`connections.json` beside user settings (respecting `XDG_CONFIG_HOME`) stores a
|
|
57
|
-
strict version-
|
|
58
|
-
allowed/current sources. It stores only credential references or an environment
|
|
79
|
+
strict version-two graph of provider switches, API metadata, source grants and per-client model deployments/defaults. Version one is read with its original single-source visibility; the first write preserves original bytes in `connections.json.v1-backup`. A null deployment list retains the legacy source catalog; an explicit array exposes only its selected deployments. Migration never expands an old `allowed` grant into model visibility. It stores only credential references or an environment
|
|
59
80
|
variable name. Keys use macOS Keychain service `codex-copilot-dx.manual-api`,
|
|
60
81
|
Windows CurrentUser DPAPI-protected bytes, or Linux Secret Service (`secret-tool`).
|
|
61
82
|
Unavailable protection fails without plaintext fallback. Headless installations
|
|
@@ -64,8 +85,8 @@ starts. Its value is never returned by management or copied into client config.
|
|
|
64
85
|
Private helpers omit unrelated credentials and Node hooks. API error bodies are
|
|
65
86
|
replaced with stable codes; valid Retry-After metadata is retained.
|
|
66
87
|
|
|
67
|
-
`client-gateway-keys.json` holds local credentials separately. Disabled sources
|
|
68
|
-
|
|
88
|
+
`client-gateway-keys.json` holds local credentials separately. Disabled sources leave normal source lists. **Model sources** owns **Disabled sources**; application access cards own **Disabled clients**. App navigation remains available while access is closed, so its restoration control stays reachable. Each
|
|
89
|
+
collapsed list appears only when it has entries and provides **Enable again**.
|
|
69
90
|
Closing a client stops CCDX access, not the app. Disabling an in-use source
|
|
70
91
|
requires explicit replacements or pauses. Pinned API streams finish on their
|
|
71
92
|
original provider; retired transports/keys are released afterwards. Legacy M365
|
|
@@ -106,6 +127,73 @@ status returns compact source/client summaries, not all model records. Metrics
|
|
|
106
127
|
allow the two built-ins plus 16 APIs (18 labels plus bounded `other`). Aggregate
|
|
107
128
|
Claude observation covers all Messages sources; M365 counts keep their own scope.
|
|
108
129
|
|
|
130
|
+
## Model capabilities and Claude synchronization
|
|
131
|
+
|
|
132
|
+
Model sources owns source credentials, native interface declarations and model details.
|
|
133
|
+
Codex/Claude own the selected deployment set, default and automatic synchronization.
|
|
134
|
+
Claude App and Claude Code have separate segments and local keys. Settings retains
|
|
135
|
+
appearance, startup and updates; source/client editors are not duplicated there.
|
|
136
|
+
|
|
137
|
+
A deployment is identified by source plus actual model ID. Its stable public route
|
|
138
|
+
is independent of catalog order and key rotation; its private history/evidence
|
|
139
|
+
identity includes endpoint, authentication and credential generation. Same-named
|
|
140
|
+
models from two sources remain separate. Old unqualified IDs/aliases resolve only
|
|
141
|
+
when unambiguous. A closed source removes its selected bindings; restoring the
|
|
142
|
+
source alone does not reopen model access. There is no intent router, load balancing,
|
|
143
|
+
model substitution, cross-source retry or automatic protocol conversion.
|
|
144
|
+
|
|
145
|
+
Each custom model accepts an optional `capabilities` object with positive token
|
|
146
|
+
limits (`context_window`, `max_input_tokens`, `max_output_tokens`), reasoning flags,
|
|
147
|
+
`reasoning_efforts`, optional reasoning budget bounds/format, `input_modalities`,
|
|
148
|
+
boolean tools/parallel tools/streaming/structured output and a `web_search` array
|
|
149
|
+
of supported native protocols. Empty arrays mean an explicit empty set; in the
|
|
150
|
+
editor enter `[]`. Blank fields follow the current deployment catalog. Known
|
|
151
|
+
numeric limits, flags and enums are strictly validated; arbitrary JSON is rejected.
|
|
152
|
+
|
|
153
|
+
Discovery retains recognized structured fields with per-deployment timestamps.
|
|
154
|
+
Manual fields, including false/empty arrays, take priority over API declarations.
|
|
155
|
+
ID-only results keep missing fields unknown. A failed refresh preserves saved
|
|
156
|
+
metadata and records a bounded error; a changed endpoint/key invalidates prior
|
|
157
|
+
catalog evidence. A listing or minimal successful reply is not a capability test.
|
|
158
|
+
Ordinary page reads use saved data and never probe each model. No public model-name
|
|
159
|
+
heuristic or original-vendor limit is applied to an arbitrary relay deployment.
|
|
160
|
+
|
|
161
|
+
Claude configuration and gateway catalogs use the same compiled model plan.
|
|
162
|
+
Explicit App bindings use opaque source-qualified aliases and actual model/source
|
|
163
|
+
labels. Verified 3.x App adapters can use a reasoning-compatible route when the
|
|
164
|
+
advertised levels form a client-expressible contiguous set. Older compatibility
|
|
165
|
+
routes remain resolvable for that authorized deployment. Gapped or unexpressible
|
|
166
|
+
levels are reported as limited; unsupported effort requests fail explicitly.
|
|
167
|
+
No tool permission or safety-review setting is disabled for compatibility.
|
|
168
|
+
|
|
169
|
+
The App Code host and independent Code share some settings. CCDX plans them once,
|
|
170
|
+
then applies field-owned changes through the existing rollback journal. A known
|
|
171
|
+
managed set entirely within 100K–1M can use the largest shared host window and
|
|
172
|
+
per-model `modelSettings.<route>.autoCompactWindow` budgets. The shared display
|
|
173
|
+
window is not each model's context limit. Unknown, 64K, above-1M or unverified
|
|
174
|
+
consumers prevent this global context override. Existing manual/managed values
|
|
175
|
+
remain unchanged. Unknown client builds retain working catalogs and report the
|
|
176
|
+
advanced host limitation. Code package/native-path version detection is read-only;
|
|
177
|
+
it does not install or run a version probe at startup.
|
|
178
|
+
|
|
179
|
+
The host output override is written only when all managed consumers declare an
|
|
180
|
+
output limit and is capped at 128K by the adapter. The gateway also clamps each
|
|
181
|
+
custom Messages/Responses request to that deployment's declared maximum, records
|
|
182
|
+
`capability_revision`/`capability_constraints`, and never deletes conversation
|
|
183
|
+
history to fit a budget. Reasoning-budget conflicts and unsupported declared
|
|
184
|
+
levels fail locally. Native search is recorded per protocol: Responses support
|
|
185
|
+
does not imply Messages support. Native tool/citation/replay data remains on the
|
|
186
|
+
existing protocol path; no shared search executor or external search account is
|
|
187
|
+
added. Exact input counting and compression thresholds are not proven by a small
|
|
188
|
+
reply; the upstream still enforces its actual limits.
|
|
189
|
+
|
|
190
|
+
Automatic sync can be disabled per client. Shared Claude fields are preserved
|
|
191
|
+
when a shared consumer has disabled automatic sync. Closing access restores owned
|
|
192
|
+
client connection fields; other active consumers retain shared planning. Review
|
|
193
|
+
sync shows declared capabilities, supported budgets and limitations. Reopen the
|
|
194
|
+
client after its owned configuration changes. All tests using sample capabilities
|
|
195
|
+
are isolated; they do not assign sample limits to a user's real models.
|
|
196
|
+
|
|
109
197
|
## Microsoft 365 provider
|
|
110
198
|
|
|
111
199
|
Starting with 0.10.0, CCDX can discover authorized M365 models independently of
|
|
@@ -1139,7 +1227,7 @@ Unknown support prevents an explicitly requested exception from starting.
|
|
|
1139
1227
|
For an older updater that still requires Git, install the Release tarball directly:
|
|
1140
1228
|
|
|
1141
1229
|
```sh
|
|
1142
|
-
npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.
|
|
1230
|
+
npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.17/codex-copilot-dx-1.2.17.tgz
|
|
1143
1231
|
# Windows PowerShell: use npm.cmd instead of npm.
|
|
1144
1232
|
```
|
|
1145
1233
|
|
package/package.json
CHANGED
package/src/access-settings.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
|
6
6
|
import { withFileLockSync } from "./lock.mjs";
|
|
7
7
|
import { isProviderId } from "./provider-metadata.mjs";
|
|
8
8
|
import { CODEX_AUTO_REVIEW_MODEL } from "./models.mjs";
|
|
9
|
+
import { validCapabilities } from "./model-capabilities.mjs";
|
|
9
10
|
|
|
10
11
|
export const CLIENT_IDS = Object.freeze(["codex", "claude_app", "claude_code"]);
|
|
11
12
|
export const CLIENT_NAMES = Object.freeze({ codex: "Codex App", claude_app: "Claude App", claude_code: "Claude Code" });
|
|
@@ -46,9 +47,12 @@ export function checkedApi(value) {
|
|
|
46
47
|
const seen = new Set();
|
|
47
48
|
for (const model of value.models) {
|
|
48
49
|
if (model?.id === CODEX_AUTO_REVIEW_MODEL) throw accessError("ccdx_api_model_reserved");
|
|
49
|
-
if (!fields(model, ["id", "protocols", "context_window", "reasoning_efforts"]) || !modelId(model.id) || seen.has(model.id)
|
|
50
|
+
if (!fields(model, ["id", "protocols", "context_window", "reasoning_efforts", "capabilities", "metadata"]) || !modelId(model.id) || seen.has(model.id)
|
|
50
51
|
|| !Array.isArray(model.protocols) || !model.protocols.length || new Set(model.protocols).size !== model.protocols.length
|
|
51
52
|
|| model.protocols.some(api => !value.endpoints[api])
|
|
53
|
+
|| model.capabilities !== undefined && !validCapabilities(model.capabilities)
|
|
54
|
+
|| model.metadata !== undefined && (!fields(model.metadata, ["values", "checked_at", "deployment"]) || !validCapabilities(model.metadata.values)
|
|
55
|
+
|| !/^[a-f0-9]{32}$/.test(model.metadata.deployment || "") || !Number.isFinite(Date.parse(model.metadata.checked_at)))
|
|
52
56
|
|| model.context_window !== undefined && (!Number.isSafeInteger(model.context_window) || model.context_window < 1)
|
|
53
57
|
|| model.reasoning_efforts !== undefined && (!Array.isArray(model.reasoning_efforts) || model.reasoning_efforts.length > 8
|
|
54
58
|
|| model.reasoning_efforts.some(effort => !["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(effort)))) throw accessError("ccdx_api_models_invalid");
|
|
@@ -58,11 +62,11 @@ export function checkedApi(value) {
|
|
|
58
62
|
return value;
|
|
59
63
|
}
|
|
60
64
|
export function defaultAccessSettings() {
|
|
61
|
-
return { version:
|
|
65
|
+
return { version: 2, claude_private_keys: false, providers: { github: true, m365: true }, apis: [], clients: Object.fromEntries(CLIENT_IDS.map(id => [id,
|
|
62
66
|
{ enabled: true, allowed: id === "codex" ? ["github", "m365"] : ["m365"], source: null }])) };
|
|
63
67
|
}
|
|
64
68
|
export function checkedAccessSettings(value) {
|
|
65
|
-
if (!fields(value, ["version", "claude_private_keys", "providers", "apis", "clients"]) || value.version
|
|
69
|
+
if (!fields(value, ["version", "claude_private_keys", "providers", "apis", "clients"]) || ![1, 2].includes(value.version) || typeof value.claude_private_keys !== "boolean"
|
|
66
70
|
|| !fields(value.providers, ["github", "m365"]) || ["github", "m365"].some(id => typeof value.providers[id] !== "boolean")
|
|
67
71
|
|| !Array.isArray(value.apis) || value.apis.length > 16 || !fields(value.clients, CLIENT_IDS)) throw accessError("ccdx_connections_invalid");
|
|
68
72
|
const ids = new Set(["github", "m365"]), names = new Set(["github copilot", "microsoft 365"]);
|
|
@@ -71,10 +75,15 @@ export function checkedAccessSettings(value) {
|
|
|
71
75
|
}
|
|
72
76
|
for (const id of CLIENT_IDS) {
|
|
73
77
|
const client = value.clients[id];
|
|
74
|
-
if (!fields(client, ["enabled", "allowed", "source", "model", "auto_review_model", "auto_review_effort", "history_isolation"])
|
|
78
|
+
if (!fields(client, ["enabled", "allowed", "source", "model", "auto_review_model", "auto_review_effort", "history_isolation", "deployments", "default_model", "auto_sync"])
|
|
75
79
|
|| typeof client.enabled !== "boolean" || !Array.isArray(client.allowed) || client.allowed.length > 18 || new Set(client.allowed).size !== client.allowed.length
|
|
76
80
|
|| client.allowed.some(source => !ids.has(source)) || client.source !== null && !client.allowed.includes(client.source)
|
|
77
81
|
|| ["model", "auto_review_model"].some(key => client[key] !== undefined && !modelId(client[key]))
|
|
82
|
+
|| client.auto_sync !== undefined && typeof client.auto_sync !== "boolean"
|
|
83
|
+
|| client.default_model !== undefined && client.default_model !== null && !modelId(client.default_model)
|
|
84
|
+
|| client.deployments !== undefined && client.deployments !== null && (!Array.isArray(client.deployments) || client.deployments.length > 1000
|
|
85
|
+
|| client.deployments.some(item => !fields(item, ["source", "model"]) || !client.allowed.includes(item.source) || !modelId(item.model))
|
|
86
|
+
|| new Set(client.deployments.map(item => item.source + "\0" + item.model)).size !== client.deployments.length)
|
|
78
87
|
|| client.history_isolation !== undefined && typeof client.history_isolation !== "boolean"
|
|
79
88
|
|| client.auto_review_effort !== undefined && client.auto_review_effort !== null && !["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(client.auto_review_effort)) throw accessError("ccdx_connections_invalid");
|
|
80
89
|
for (const source of client.allowed) {
|
|
@@ -82,6 +91,10 @@ export function checkedAccessSettings(value) {
|
|
|
82
91
|
if (!apis.includes(id === "codex" ? "responses" : "messages")) throw accessError("ccdx_api_protocol_required");
|
|
83
92
|
}
|
|
84
93
|
}
|
|
94
|
+
if (value.version === 1) {
|
|
95
|
+
value = structuredClone(value);value.version = 2;
|
|
96
|
+
for (const client of Object.values(value.clients)) { client.deployments = null;client.auto_sync = true; }
|
|
97
|
+
}
|
|
85
98
|
return value;
|
|
86
99
|
}
|
|
87
100
|
export function readAccessSettings(options = {}) {
|
|
@@ -93,6 +106,11 @@ export function updateAccessSettings(change, options = {}) {
|
|
|
93
106
|
return withFileLockSync(`${file}.lock`, () => {
|
|
94
107
|
const next = checkedAccessSettings(change(readAccessSettings(options)));
|
|
95
108
|
const text = JSON.stringify(next, null, 2) + "\n";if (Buffer.byteLength(text) > 8 * 1024 * 1024) throw accessError("ccdx_connections_limit", 413);
|
|
109
|
+
// Preserve the original v1 bytes once, before the first v2 write.
|
|
110
|
+
try {
|
|
111
|
+
const original = readBoundedFileSync(file, { maxBytes: 8 * 1024 * 1024, encoding: "utf8" });
|
|
112
|
+
if (JSON.parse(original).version === 1 && !fs.existsSync(`${file}.v1-backup`)) atomicWriteFileSync(`${file}.v1-backup`, original, { mode: 0o600 });
|
|
113
|
+
} catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
96
114
|
atomicWriteFileSync(file, text, { mode: 0o600 });return next;
|
|
97
115
|
});
|
|
98
116
|
}
|
package/src/adapter.mjs
CHANGED
|
@@ -103,7 +103,10 @@ async function sendModelList(res, models, {
|
|
|
103
103
|
providerCatalog,
|
|
104
104
|
} = {}) {
|
|
105
105
|
let body = rawBody || JSON.stringify(models);
|
|
106
|
-
if (clientVersion && typeof providerCatalog === "function")
|
|
106
|
+
if (clientVersion && typeof providerCatalog === "function") {
|
|
107
|
+
const catalog = providerCatalog.needsNativeCatalog && codexModelCatalog?.load ? await codexModelCatalog.load({ clientVersion }) : null;
|
|
108
|
+
body = JSON.stringify(providerCatalog(models, catalog));
|
|
109
|
+
}
|
|
107
110
|
else if (clientVersion && typeof codexModelCatalog?.load === "function") {
|
|
108
111
|
let response = null;
|
|
109
112
|
try {
|
|
@@ -201,6 +204,8 @@ export function createAdapterHandler(options = {}) {
|
|
|
201
204
|
});
|
|
202
205
|
const responsesHandler = createResponsesHandler({
|
|
203
206
|
validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
|
|
207
|
+
resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
|
|
208
|
+
providerPreference: id => options.providerRuntime?.providerPreference?.(id),
|
|
204
209
|
provider: options.provider || options.providerRuntime?.github,
|
|
205
210
|
acquireRequest,
|
|
206
211
|
autoReviewModelResolver: options.autoReviewModelResolver,
|
|
@@ -221,6 +226,8 @@ export function createAdapterHandler(options = {}) {
|
|
|
221
226
|
});
|
|
222
227
|
const responsesCompactHandler = createResponsesCompactHandler({
|
|
223
228
|
validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
|
|
229
|
+
resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
|
|
230
|
+
providerPreference: id => options.providerRuntime?.providerPreference?.(id),
|
|
224
231
|
provider: options.provider || options.providerRuntime?.github,
|
|
225
232
|
acquireRequest,
|
|
226
233
|
autoReviewModelResolver: options.autoReviewModelResolver,
|
|
@@ -241,6 +248,8 @@ export function createAdapterHandler(options = {}) {
|
|
|
241
248
|
if (!providerHandlers.has(provider)) {
|
|
242
249
|
const common = { provider, acquireRequest, imagePressure, keepaliveIntervalMs: options.keepaliveIntervalMs,
|
|
243
250
|
validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
|
|
251
|
+
resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
|
|
252
|
+
providerPreference: id => options.providerRuntime?.providerPreference?.(id),
|
|
244
253
|
modelRegistry: provider.registry, now: options.now, openAIModelEnv: { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" },
|
|
245
254
|
autoReviewModelResolver: () => { const preference = options.providerRuntime.providerPreference?.(provider.id) || options.providerRuntime.selection().m365;
|
|
246
255
|
return { model: preference?.auto_review_model, reasoningEffort: preference?.auto_review_effort === undefined ? Object.hasOwn(provider, "defaultReviewEffort") ? provider.defaultReviewEffort : "low" : preference.auto_review_effort }; },
|
|
@@ -282,7 +291,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
282
291
|
try { target = options.providerRuntime.current(req); }
|
|
283
292
|
catch (error) { sendJsonError(res, error, 503);return; }
|
|
284
293
|
const context = currentRequestContext();
|
|
285
|
-
if (context) {
|
|
294
|
+
if (context && !(req.method === "POST" && options.providerRuntime.hasModelBindings?.())) {
|
|
286
295
|
context.provider = target.id;
|
|
287
296
|
context.streamPerformance?.setProvider?.(target.id);
|
|
288
297
|
context.finishProvider = options.providerRuntime.track?.(target);
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
4
|
+
import { m365Paths, readM365Json } from "./m365-settings.mjs";
|
|
5
|
+
import { claudeEffortsExpressible } from "./model-capabilities.mjs";
|
|
6
|
+
import { claudeModelEntries } from "./claude-models.mjs";
|
|
7
|
+
import { claudeClientPaths, reconcileClaudeConfiguration } from "./claude-client-config.mjs";
|
|
8
|
+
|
|
9
|
+
export function inspectClaudeCapabilitySupport({ platform = process.platform, env = process.env, appVersion, codeVersion } = {}) {
|
|
10
|
+
if (!codeVersion) for (const directory of (env.PATH || "").split(path.delimiter).filter(Boolean)) {
|
|
11
|
+
try {
|
|
12
|
+
const executable = fs.realpathSync(path.join(directory, platform === "win32" ? "claude.exe" : "claude"));
|
|
13
|
+
codeVersion = /[\\/]versions[\\/](2\.1\.\d+)(?:\.exe)?(?:[\\/]|$)/.exec(executable)?.[1];
|
|
14
|
+
let parent = path.dirname(executable);
|
|
15
|
+
for (let i = 0; !codeVersion && i < 4; i++, parent = path.dirname(parent)) {
|
|
16
|
+
try { const value = JSON.parse(readBoundedFileSync(path.join(parent, "package.json"), { maxBytes: 65536, encoding: "utf8" }));if (value.name === "@anthropic-ai/claude-code") codeVersion = value.version; } catch { /* Native installs may encode their version in the resolved path. */ }
|
|
17
|
+
}
|
|
18
|
+
break;
|
|
19
|
+
} catch { /* No executable in this PATH entry. */ }
|
|
20
|
+
}
|
|
21
|
+
if (!appVersion && platform === "darwin") {
|
|
22
|
+
try { appVersion = /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(readBoundedFileSync("/Applications/Claude.app/Contents/Info.plist", { maxBytes: 65536, encoding: "utf8" }))?.[1]; } catch { /* Unknown builds keep the conservative alias. */ }
|
|
23
|
+
}
|
|
24
|
+
// The 3.x App schema/host was independently inspected. Other versions keep
|
|
25
|
+
// working catalogs without claiming adoption of undocumented host controls.
|
|
26
|
+
return { app_version: appVersion || null, app: /^3\./.test(appVersion || ""), code_version: codeVersion || null, code: /^2\.1\./.test(codeVersion || "") && Number(codeVersion.split(".")[2]) >= 293 };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function claudeSharedCapabilityPlan({ app = [], code = [], support = {} } = {}) {
|
|
30
|
+
const limitations = [], budgets = {}, caps = [], consumers = [...app.map(model => ({ model, app: true })), ...code.map(model => ({ model, app: false }))];
|
|
31
|
+
let context = 0, output = 0, safeContext = consumers.length > 0, knownAdapters = true;
|
|
32
|
+
for (const { model, app: desktop } of consumers) {
|
|
33
|
+
const entry = claudeModelEntries([model], { desktopAliases: desktop })[0], values = model.capability?.values || {};
|
|
34
|
+
const id = model.public_id || entry.name;
|
|
35
|
+
if (desktop ? !support.app : !support.code) { safeContext = false;knownAdapters = false;limitations.push({ model: model.id, code: "client_version_unknown" });continue; }
|
|
36
|
+
const window = values.context_window;
|
|
37
|
+
if (!window) { safeContext = false;limitations.push({ model: model.id, code: "context_unknown" }); }
|
|
38
|
+
else if (window < 100000 || window > 1000000) { safeContext = false;limitations.push({ model: model.id, code: "context_range_limited", value: window }); }
|
|
39
|
+
else { context = Math.max(context, window);budgets[id] = Math.min(window, values.max_input_tokens || window); }
|
|
40
|
+
if (budgets[id] && budgets[id] < 100000) { safeContext = false;delete budgets[id];limitations.push({ model: model.id, code: "context_range_limited" }); }
|
|
41
|
+
output = Math.max(output, values.max_output_tokens || 0);
|
|
42
|
+
const efforts = values.reasoning === false ? [] : values.reasoning_efforts || [];
|
|
43
|
+
if (efforts.length && !claudeEffortsExpressible(values)) limitations.push({ model: model.id, code: "reasoning_levels_limited" });
|
|
44
|
+
if (claudeEffortsExpressible(values)) caps.push(`${id.toLowerCase()}=${["effort", ...(efforts.includes("xhigh") ? ["xhigh_effort"] : []), ...(efforts.includes("max") ? ["max_effort"] : [])].join(",")}`);
|
|
45
|
+
if (values.web_search && !values.web_search.includes("messages")) limitations.push({ model: model.id, code: "search_messages_unavailable" });
|
|
46
|
+
}
|
|
47
|
+
if (!safeContext) context = 0;
|
|
48
|
+
const capabilities = caps.join(";");
|
|
49
|
+
if (capabilities.length > 8000) limitations.push({ code: "capability_list_limited" });
|
|
50
|
+
return { state: consumers.length ? "planned" : "not_configured", context_tokens: context || null,
|
|
51
|
+
output_tokens: output && knownAdapters && consumers.every(({ model }) => model.capability?.values.max_output_tokens) ? Math.min(output, 128000) : null, budgets: context ? budgets : {},
|
|
52
|
+
capabilities: capabilities.length <= 8000 ? capabilities : "", limitations };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function syncClaudeCapabilities(plan, options = {}) {
|
|
56
|
+
const paths = claudeClientPaths(options), env = options.env || process.env;
|
|
57
|
+
let current = {};try { current = JSON.parse(readBoundedFileSync(paths.code, { maxBytes: 1024 * 1024, encoding: "utf8" })); }
|
|
58
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
59
|
+
const operations = [], add = (keys, value) => operations.push({ file: paths.code, keys, value });
|
|
60
|
+
// An independently configured Code consumer also reads this file. Preserve
|
|
61
|
+
// its host boundary instead of letting the App change it indirectly.
|
|
62
|
+
const base = env.ANTHROPIC_BASE_URL || current.env?.ANTHROPIC_BASE_URL;
|
|
63
|
+
const journal = readM365Json(m365Paths(options).ownership, { version: 1, operations: [] });
|
|
64
|
+
const ownsCodeBase = journal.operations?.some(op => op.file === paths.code && op.keys?.join(".") === "env.ANTHROPIC_BASE_URL" && op.after === base);
|
|
65
|
+
const conflict = Boolean(env.ANTHROPIC_BASE_URL || base && (!/^http:\/\/127\.0\.0\.1:\d+\/anthropic$/.test(base) || !ownsCodeBase));
|
|
66
|
+
const ownedFields = ["env.CLAUDE_CODE_MAX_CONTEXT_TOKENS", "env.CLAUDE_CODE_MAX_OUTPUT_TOKENS", "env.CLAUDE_CODE_MODEL_CAPABILITIES"];
|
|
67
|
+
if (!conflict) {
|
|
68
|
+
for (const [key, value] of [["CLAUDE_CODE_MAX_CONTEXT_TOKENS", plan.context_tokens], ["CLAUDE_CODE_MAX_OUTPUT_TOKENS", plan.output_tokens], ["CLAUDE_CODE_MODEL_CAPABILITIES", plan.capabilities]]) {
|
|
69
|
+
if (value && env[key] === undefined) add(["env", key], String(value));
|
|
70
|
+
}
|
|
71
|
+
for (const [id, value] of Object.entries(plan.budgets)) add(["modelSettings", id, "autoCompactWindow"], value);
|
|
72
|
+
}
|
|
73
|
+
const active = new Set(operations.map(op => op.keys.join(".")));
|
|
74
|
+
const restored = reconcileClaudeConfiguration([], { ...options, restore: true,
|
|
75
|
+
selectOperation: op => op.file === paths.code && (ownedFields.includes(op.keys.join(".")) || op.keys[0] === "modelSettings" && op.keys[2] === "autoCompactWindow") && !active.has(op.keys.join(".")) });
|
|
76
|
+
const result = reconcileClaudeConfiguration(operations, options);
|
|
77
|
+
return { state: conflict || result.preserved || restored.preserved ? "partially_preserved" : operations.length ? "configured" : "limited",
|
|
78
|
+
changed: result.changed || restored.changed, preserved: result.preserved + restored.preserved,
|
|
79
|
+
restart_required: result.changed || restored.changed };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function inspectClaudeCapabilityConfiguration(models, options = {}) {
|
|
83
|
+
let settings = {};
|
|
84
|
+
try { settings = JSON.parse(readBoundedFileSync(claudeClientPaths(options).code, { maxBytes: 1024 * 1024, encoding: "utf8" })); }
|
|
85
|
+
catch (error) { if (error.code !== "ENOENT") return { state: "configuration_unavailable" }; }
|
|
86
|
+
const integer = value => /^\d{1,9}$/.test(String(value)) && Number(value) > 0 ? Number(value) : null;
|
|
87
|
+
return { state: "read", context_tokens: integer(settings.env?.CLAUDE_CODE_MAX_CONTEXT_TOKENS), output_tokens: integer(settings.env?.CLAUDE_CODE_MAX_OUTPUT_TOKENS),
|
|
88
|
+
budgets: Object.fromEntries(models.map(model => [model.public_id, integer(settings.modelSettings?.[model.public_id]?.autoCompactWindow)])) };
|
|
89
|
+
}
|
|
@@ -87,28 +87,32 @@ function setOperation(snapshot, operation, value) {
|
|
|
87
87
|
setAt(snapshot, operation.keys, { exists: true, value: next });
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
-
function
|
|
90
|
+
export function reconcileClaudeConfiguration(operations, { restore = false, ...options } = {}) {
|
|
91
91
|
const paths = claudeClientPaths(options), allowed = new Set(Object.values(paths)), journalPath = m365Paths(options).ownership;
|
|
92
92
|
fs.mkdirSync(path.dirname(journalPath), { recursive: true, mode: 0o700 });
|
|
93
93
|
return withFileLockSync(`${journalPath}.lock`, () => {
|
|
94
94
|
const journal = readM365Json(journalPath, { version: 1, operations: [] });
|
|
95
95
|
const keys = new Map([
|
|
96
|
-
[paths.code, new Set(["env.ANTHROPIC_BASE_URL", "env.ANTHROPIC_AUTH_TOKEN", "env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY", "env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS", "env.ANTHROPIC_CUSTOM_HEADERS", "env.ANTHROPIC_MODEL"])],
|
|
96
|
+
[paths.code, new Set(["env.ANTHROPIC_BASE_URL", "env.ANTHROPIC_AUTH_TOKEN", "env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY", "env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS", "env.ANTHROPIC_CUSTOM_HEADERS", "env.ANTHROPIC_MODEL", "env.CLAUDE_CODE_MAX_CONTEXT_TOKENS", "env.CLAUDE_CODE_MAX_OUTPUT_TOKENS", "env.CLAUDE_CODE_MODEL_CAPABILITIES"])],
|
|
97
97
|
[paths.normal, new Set(["deploymentMode"])], [paths.threep, new Set(["deploymentMode"])],
|
|
98
98
|
[paths.meta, new Set(["entries", "appliedId"])],
|
|
99
99
|
[paths.profile, new Set(["inferenceProvider", "inferenceGatewayBaseUrl", "inferenceGatewayApiKey", "inferenceGatewayAuthScheme", "inferenceModels", "inferenceCustomHeaders"])],
|
|
100
100
|
]);
|
|
101
|
+
const safeKeys = op => Array.isArray(op.keys) && !op.keys.some(key => ["__proto__", "constructor", "prototype"].includes(key))
|
|
102
|
+
&& (keys.get(op.file)?.has(op.keys.join(".")) || op.file === paths.code && op.keys.length === 3 && op.keys[0] === "modelSettings"
|
|
103
|
+
&& /^[\w][\w./:@+\[\]-]{0,200}$/.test(op.keys[1]) && op.keys[2] === "autoCompactWindow");
|
|
101
104
|
if (journal.version !== 1 || !Array.isArray(journal.operations) || journal.operations.some(op => !allowed.has(op.file)
|
|
102
|
-
|| !
|
|
105
|
+
|| !safeKeys(op)
|
|
103
106
|
|| op.itemId !== undefined && (op.file !== paths.meta || op.keys.join(".") !== "entries" || op.itemId !== M365_CLAUDE_PROFILE_ID))) {
|
|
104
107
|
throw new Error("Claude configuration ownership is invalid; files were preserved");
|
|
105
108
|
}
|
|
106
109
|
const states = new Map(), pending = [], nextJournal = structuredClone(journal), skipped = [];
|
|
107
|
-
const
|
|
110
|
+
const sharedOperation = op => op.file === paths.code && (op.keys[0] === "modelSettings" || ["CLAUDE_CODE_MAX_CONTEXT_TOKENS", "CLAUDE_CODE_MAX_OUTPUT_TOKENS", "CLAUDE_CODE_MODEL_CAPABILITIES"].includes(op.keys[1]));
|
|
111
|
+
const forClient = op => (!options.selectOperation || options.selectOperation(op)) && (!options.client || (options.client === "claude_code" ? op.file === paths.code && !sharedOperation(op) : op.file !== paths.code))
|
|
108
112
|
&& (!options.fields || options.fields.includes(op.keys.join(".")));
|
|
109
113
|
const list = restore ? journal.operations.filter(forClient) : operations;
|
|
110
114
|
for (const operation of list) {
|
|
111
|
-
if (!allowed.has(operation.file)) throw new Error("Unexpected Claude configuration path");
|
|
115
|
+
if (!allowed.has(operation.file) || !safeKeys(operation)) throw new Error("Unexpected Claude configuration path");
|
|
112
116
|
if (!states.has(operation.file)) states.set(operation.file, read(operation.file));
|
|
113
117
|
const state = states.get(operation.file);state.next ||= structuredClone(state.value);
|
|
114
118
|
const previous = journal.operations.find(op => op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId);
|
|
@@ -154,7 +158,7 @@ function reconcile(operations, { restore = false, ...options } = {}) {
|
|
|
154
158
|
});
|
|
155
159
|
}
|
|
156
160
|
|
|
157
|
-
export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, profileName = M365_CLAUDE_PROFILE_NAME, disableExperimentalBetas = true, ...options } = {}) {
|
|
161
|
+
export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, desktopAliases = false, profileName = M365_CLAUDE_PROFILE_NAME, disableExperimentalBetas = true, defaultModel, ...options } = {}) {
|
|
158
162
|
const entries = claudeModelEntries(models);
|
|
159
163
|
const paths = claudeClientPaths(options), ids = entries.map(model => model.name), operations = [], result = {};
|
|
160
164
|
const endpoint = new URL(baseUrl);
|
|
@@ -187,7 +191,7 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
|
|
|
187
191
|
if (ids.length && (!codeEnv.ANTHROPIC_MODEL || models.some(model => model.id === codeEnv.ANTHROPIC_MODEL)
|
|
188
192
|
|| owns(paths.code, ["env", "ANTHROPIC_MODEL"], codeEnv.ANTHROPIC_MODEL))) {
|
|
189
193
|
const index = models.findIndex(model => model.id === codeEnv.ANTHROPIC_MODEL || claudeClientModelId(model.id) === codeEnv.ANTHROPIC_MODEL);
|
|
190
|
-
add(paths.code, ["env", "ANTHROPIC_MODEL"], ids[Math.max(0, index)]);
|
|
194
|
+
add(paths.code, ["env", "ANTHROPIC_MODEL"], defaultModel && ids.includes(defaultModel) ? defaultModel : ids[Math.max(0, index)]);
|
|
191
195
|
}
|
|
192
196
|
result.code = "configured";
|
|
193
197
|
}
|
|
@@ -216,7 +220,13 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
|
|
|
216
220
|
const name = typeof entry === "string" ? entry : entry?.name;
|
|
217
221
|
return [typeof name === "string" ? claudeClientModelId(name) : "", index];
|
|
218
222
|
}));
|
|
219
|
-
const
|
|
223
|
+
const desktopEntries = desktopAliases ? claudeModelEntries(models, { desktopAliases }) : entries;
|
|
224
|
+
for (let index = 0; index < models.length; index++) {
|
|
225
|
+
const old = order.get(claudeClientModelId(models[index].id));
|
|
226
|
+
if (old !== undefined && !order.has(desktopEntries[index].name)) order.set(desktopEntries[index].name, old);
|
|
227
|
+
}
|
|
228
|
+
const orderedEntries = [...desktopEntries].sort((left, right) => defaultModel && (left.name === defaultModel || right.name === defaultModel)
|
|
229
|
+
? left.name === defaultModel ? -1 : 1 : (order.get(left.name) ?? Infinity) - (order.get(right.name) ?? Infinity));
|
|
220
230
|
add(paths.profile, ["inferenceModels"], JSON.stringify(orderedEntries));
|
|
221
231
|
add(paths.profile, ["inferenceCustomHeaders"], JSON.stringify({ "X-CCDX-Client": "claude-app" }));
|
|
222
232
|
add(paths.meta, ["entries"], { id: M365_CLAUDE_PROFILE_ID, name: profileName }, M365_CLAUDE_PROFILE_ID);
|
|
@@ -225,7 +235,7 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
|
|
|
225
235
|
result.app = "configured";
|
|
226
236
|
}
|
|
227
237
|
}
|
|
228
|
-
const applied =
|
|
238
|
+
const applied = reconcileClaudeConfiguration(operations, options);
|
|
229
239
|
if (applied.preserved) {
|
|
230
240
|
if (result.code === "configured") result.code = "partially_preserved";
|
|
231
241
|
if (result.app === "configured") result.app = "partially_preserved";
|
|
@@ -235,5 +245,5 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
|
|
|
235
245
|
|
|
236
246
|
export function restoreClaudeClients(options = {}) {
|
|
237
247
|
if (!fs.existsSync(m365Paths(options).ownership)) return { changed: false, preserved: 0, remaining: 0 };
|
|
238
|
-
return
|
|
248
|
+
return reconcileClaudeConfiguration([], { ...options, restore: true });
|
|
239
249
|
}
|