codex-copilot-dx 1.3.26 → 1.3.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -2
- package/bin/cli.mjs +5 -2
- package/docs/ARCHITECTURE.md +16 -3
- package/docs/REFERENCE.md +28 -4
- package/package.json +1 -1
- package/src/adapter.mjs +4 -2
- package/src/claude-app-contract.mjs +96 -0
- package/src/claude-capability-config.mjs +26 -10
- package/src/claude-client-config.mjs +56 -7
- package/src/claude-gateway.mjs +7 -5
- package/src/claude-models.mjs +4 -2
- package/src/cli-command-spec.mjs +8 -2
- package/src/cli-management.mjs +26 -6
- package/src/client-versions.mjs +17 -13
- package/src/connection-client-sync.mjs +1 -0
- package/src/connection-management.mjs +5 -0
- package/src/connection-policy.mjs +2 -2
- package/src/connection-routing.mjs +2 -1
- package/src/connection-runtime.mjs +26 -2
- package/src/connection-view.mjs +11 -2
- package/src/dashboard/connections.js +33 -3
- package/src/dashboard/console.js +1 -1
- package/src/dashboard/context.js +8 -4
- package/src/dashboard/gemini.js +3 -7
- package/src/dashboard/index.html +5 -2
- package/src/dashboard/language.js +24 -0
- package/src/dashboard/status.js +8 -1
- package/src/dashboard/ui.js +3 -0
- package/src/dashboard-api.mjs +2 -2
- package/src/doctor-compat.mjs +1 -1
- package/src/model-capabilities.mjs +17 -4
- package/src/provider-cooldown.mjs +43 -0
- package/src/providers/api-model-metadata.mjs +7 -0
- package/src/providers/api.mjs +32 -11
- package/src/request-context.mjs +5 -0
- package/src/response-failures.mjs +4 -2
- package/src/safe-upstream-error.mjs +36 -4
- package/src/source-import.mjs +51 -0
- package/src/stream-performance.mjs +7 -5
- package/src/usage-analysis.mjs +2 -2
- package/src/usage-query.mjs +5 -2
- package/src/usage-store.mjs +2 -1
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Use your model services in **Codex App, Claude App and Claude Code** through one local gateway.
|
|
4
4
|
|
|
5
|
-
On macOS, the optional Gemini integration adds Copilot Carbon and Argon to the original App's Antigravity. Ordinary Gemini chat keeps Google. The Antigravity page lists each model once, with its reasoning
|
|
5
|
+
On macOS, the optional Gemini integration adds Copilot Carbon and Argon to the original App's Antigravity. Ordinary Gemini chat keeps Google. The Antigravity page lists each model once, with its supported reasoning levels shown in the same format as Codex and Claude. Inspect it with `ccdx app antigravity status`. Existing clients keep their setup.
|
|
6
6
|
|
|
7
7
|
Connect GitHub Copilot, Microsoft 365 or your own API. Choose which apps can use each source, then select their models. CI and prebuilt releases cover **macOS on Apple Silicon** and **Windows on x64/ARM64**. Intel Mac code remains available, without CI coverage or new prebuilt assets.
|
|
8
8
|
|
|
@@ -35,6 +35,8 @@ The Web UI opens at [http://127.0.0.1:2026](http://127.0.0.1:2026/). Run `ccdx w
|
|
|
35
35
|
3. **Overview / Requests:** check configuration, activity and errors.
|
|
36
36
|
4. **Usage → Context:** inspect reported input, model windows and observed compactions from this run.
|
|
37
37
|
|
|
38
|
+
Claude capability synchronization checks the installed macOS App contract when it changes. Compatible upgrades can keep their model identities and reasoning controls without a CCDX version-list update. Reopen Claude normally after native configuration changes. Inspect synchronization and observed effort with `ccdx app claude-app status --details`.
|
|
39
|
+
|
|
38
40
|
For a custom API, enter its HTTPS address and key, then choose **Save & read models**. Select the models and interfaces it provides. Codex uses Responses; Claude uses Messages. Both share port 2026.
|
|
39
41
|
|
|
40
42
|
Model availability depends on your account and service. Microsoft 365 also requires a supported company environment. Existing account, model and client settings are retained during upgrades. No repeat setup or model selection is needed for an unchanged working configuration.
|
|
@@ -46,13 +48,14 @@ Model availability depends on your account and service. Microsoft 365 also requi
|
|
|
46
48
|
| Start the gateway | `ccdx` |
|
|
47
49
|
| Open the Web UI | `ccdx web` |
|
|
48
50
|
| Check service and apps | `ccdx status` / `ccdx app list` |
|
|
51
|
+
| Preview imported APIs | `ccdx source import --file providers.json` |
|
|
49
52
|
| Manage sources | `ccdx source list` / `ccdx source add` |
|
|
50
53
|
| Sign in again | `ccdx source github reauth` |
|
|
51
54
|
| Choose client models | `ccdx app codex models --edit` |
|
|
52
55
|
| Preview client setup | `ccdx app claude-app sync --preview` |
|
|
53
56
|
| Set up Antigravity | `ccdx app antigravity status` / `enable` / `open` |
|
|
54
57
|
| Inspect failures | `ccdx requests --failed` |
|
|
55
|
-
| Read usage | `ccdx usage` / `ccdx usage --provider google --days 7` / `ccdx usage --scope run` |
|
|
58
|
+
| Read usage | `ccdx usage` / `ccdx usage --provider google --days 7` / `ccdx usage --purpose diagnostic` / `ccdx usage --scope run` |
|
|
56
59
|
| Inspect preferences | `ccdx config show --effective` |
|
|
57
60
|
| Inspect local masking | `ccdx config privacy status` |
|
|
58
61
|
| Check local setup | `ccdx doctor` |
|
package/bin/cli.mjs
CHANGED
|
@@ -329,9 +329,12 @@ const clientVersions = {
|
|
|
329
329
|
snapshot: () => versionMonitor?.snapshot() || null,
|
|
330
330
|
refresh() {
|
|
331
331
|
if (shuttingDown || serviceWorker?.warming || serviceWorker?.draining || serviceWorker?.preserving) return Promise.resolve(clientVersions.snapshot());
|
|
332
|
-
versionModule ||= import("../src/client-versions.mjs").then(({ createClientVersionMonitor }) => {
|
|
332
|
+
versionModule ||= import("../src/client-versions.mjs").then(({ createClientVersionMonitor, clientVersionName }) => {
|
|
333
333
|
if (shuttingDown) return null;
|
|
334
|
-
versionMonitor = createClientVersionMonitor({ onChange: names =>
|
|
334
|
+
versionMonitor = createClientVersionMonitor({ onChange: names => {
|
|
335
|
+
console.log(status("info", `Installed ${names.map(clientVersionName).join(" and ")} updated; checking managed capability configuration`));
|
|
336
|
+
if(names.includes("claude"))void providerRuntime?.refreshClientCapabilities?.().catch(()=>{});
|
|
337
|
+
} });
|
|
335
338
|
return versionMonitor;
|
|
336
339
|
}).catch(error => { versionModule = null;throw error; });
|
|
337
340
|
return versionModule.then(monitor => monitor?.refresh());
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -19,7 +19,7 @@ Client integration, image tools and the dashboard are not a general plugin frame
|
|
|
19
19
|
|
|
20
20
|
`antigravity-usage.mjs` observes Google JSON/SSE within the original forwarding loop, with the existing SSE byte limit and no stream tee or read-ahead. Observation failures mark usage unavailable and never change response bytes. The handler coalesces reported numeric fields and settles one usage row per request, including usage received before failure/cancellation. Google candidate/thought output and prompt/tool-use input are normalized without treating missing cache counts as zero. Request ID, original model, actual model and usage availability are scalar metadata; prompts and response text are not persisted by this observer.
|
|
21
21
|
|
|
22
|
-
The management snapshot keeps native per-effort aliases in `models` and adds `model_groups` for one model row with several reasoning choices. Saved alias subsets and the native catalog are unchanged. The WebUI and
|
|
22
|
+
The management snapshot keeps native per-effort aliases in `models` and adds `model_groups` for one model row with several reasoning choices. Saved alias subsets and the native catalog are unchanged. The WebUI groups selection by model and renders supported effort levels as read-only capability text, matching the Codex/Claude tables. Existing route subsets survive a model off/on toggle; CLI effort editing and JSON aliases remain compatible.
|
|
23
23
|
|
|
24
24
|
Antigravity tool schemas are converted to Chat Completions schemas. Object schemas always include an explicit `properties` map, including zero-argument functions. The upstream Copilot service rejects native schemas that omit that map. Pausing Copilot access keeps model choices visible while generation remains gated.
|
|
25
25
|
|
|
@@ -1167,7 +1167,7 @@ Performance comparison is separate from runtime logic and reports paired timing
|
|
|
1167
1167
|
|
|
1168
1168
|
The 1.3.13 native helper groups uncached short CPU sequences under the existing shared core budget. Groups retain at most 512 total tokens and 16 KiB text. The existing core budget is divided between sequence workers, including its remainder, instead of repeatedly creating a full-budget partition for every short field. Tokenization, position IDs, attention scope and dynamic quantization remain per sequence. Already-known windows and single uncached sequences retain their previous paths; long and accelerator-eligible windows use the existing reader. Cancellation waits for physical acknowledgement, completed windows remain reusable, and the complete check still precedes upstream calls. Status advertises cpu_short_batch and reports cpu_batch_groups/cpu_batch_windows without retaining values.
|
|
1169
1169
|
|
|
1170
|
-
|
|
1170
|
+
`claude-app-contract.mjs` reads bounded installed macOS archive declarations and consumers, extracts native effort profiles, and caches by installation identity. Lightweight file hints and the existing refresh path coalesce revalidation outside inference. `connection-runtime.mjs` replaces the capability snapshot and clears compiled plans before owned synchronization. Profile entries and discovery replies carry identical `behavesAs`/`behaves_as` and effort caps. Neutral route identity stays source-qualified; previously published aliases remain resolvable. Legacy inspected adapters remain available when a newer native contract cannot be checked. Non-contiguous effort sets are declared as limited instead of remapped. Shared capability-map reconciliation preserves manual entries and unchanged original restoration state. Native profile loading may require a normal client restart; requested and sent effort observations do not establish unobserved picker adoption.
|
|
1171
1171
|
|
|
1172
1172
|
Usage presentation maps configured api_ identifiers to current provider labels after aggregation. Rows, chart filters and historical statistics keep their original keys. Provider-label changes refresh only the table/model labels, preserving the selected raw model key, day and existing chart nodes. The native capability replay disables usage persistence and gives its process a temporary usage path; no production filter recognizes test model names or response IDs.
|
|
1173
1173
|
|
|
@@ -1195,8 +1195,21 @@ The managed Codex catalog projects explicit source input modalities ahead of nat
|
|
|
1195
1195
|
|
|
1196
1196
|
## Client updates and streaming boundaries
|
|
1197
1197
|
|
|
1198
|
-
`client-versions.mjs` inspects bounded local App metadata asynchronously after service readiness. It coalesces checks, preserves a corrupt observation file, and atomically records only installed versions, builds and change times. A timed-out inspection cannot block service startup or inference. The current App process and actual capability adoption remain unverified.
|
|
1198
|
+
`client-versions.mjs` inspects bounded local App metadata asynchronously after service readiness. It coalesces checks, preserves a corrupt observation file, and atomically records only installed versions, builds and change times. A timed-out inspection cannot block service startup or inference. The current App process and actual capability adoption remain unverified. Version changes also trigger Claude contract revalidation. A changed installation identity invalidates contract and compiled-plan caches, while unsupported controls preserve their owned fields. The existing model-refresh timer, manual checks and a nonblocking service-reuse notification schedule observation; a disabled timer leaves startup and manual checks available.
|
|
1199
1199
|
|
|
1200
1200
|
The Codex catalog retains at most two previously verified bundled catalogs in memory when the client supplies an exact prerelease/build version. A binary identity change during extraction, or two binaries reporting the same exact version, prevents that retained fallback. Requests containing only a core version keep their existing matching behavior and report its limited precision. No catalog is fetched from the network and no new persistent model cache is introduced.
|
|
1201
1201
|
|
|
1202
1202
|
Responses and Messages parsers, Chat line reading and the privacy restoration layer accept LF, CRLF and CR SSE lines. Existing output ordering, retry eligibility, error handling, comment heartbeats and backpressure remain. Source-lock cancellation signals reach both Responses handlers without changing ownership rules.
|
|
1203
|
+
|
|
1204
|
+
|
|
1205
|
+
### API diagnostics, request purpose, cooldown and import
|
|
1206
|
+
|
|
1207
|
+
`safe-upstream-error.mjs` reads failure bodies within existing time/size/concurrency bounds. Only fixed categories, allowlisted parameter paths and bounded technical maxima leave the reader. The API wrapper adds source/model/protocol and local request identity, retaining a safe upstream request ID. Default failure evidence excludes vendor messages and payloads.
|
|
1208
|
+
|
|
1209
|
+
`model-capabilities.mjs` validates explicit limits and protocol-scoped supported-parameter lists. Unknown declarations remain absent. `provider-cooldown.mjs` holds three bounded interface states per API instance. Two confirmed transport failures or temporary server failures open a five-second cooldown, extended by bounded Retry-After. One real request becomes the recovery attempt; client cancellation leaves recovery available. Credential/config instance replacement resets this state. No traffic is switched or replayed by cooldown.
|
|
1210
|
+
|
|
1211
|
+
The API provider reuses a cached healthy network directly. Its Messages alias table is validated and built lazily once per provider instance. Configuration changes replace that instance and its table; ambiguous catalogs retain their original rejection behavior.
|
|
1212
|
+
|
|
1213
|
+
The request context validates a scalar purpose enum. New usage rows and bounded request metrics carry the purpose; the query layer treats missing legacy tags as unknown. Default totals retain every purpose and existing failure/partial/unknown accounting. Compatibility doctor requests set the local purpose header, which is not a vendor credential or payload field.
|
|
1214
|
+
|
|
1215
|
+
`source-import.mjs` interprets only supplied bounded JSON shapes and returns metadata drafts. It invokes existing API validation, removes foreign cached evidence and credential values, reports conflicts, and grants no client access. WebUI draft review reuses the API editor; explicit CLI application reuses the existing save transaction and private key input. No foreign account discovery, executable config loading or multi-source automatic application runs.
|
package/docs/REFERENCE.md
CHANGED
|
@@ -11,6 +11,7 @@ For installation and first use, start with the [README](../README.md). This refe
|
|
|
11
11
|
| `ccdx` / `ccdx start` | Start or reuse the foreground gateway |
|
|
12
12
|
| `ccdx web` | Open the Web UI, or start management without signing in |
|
|
13
13
|
| `ccdx status` | Show runtime and app configuration; `--details` expands diagnostics |
|
|
14
|
+
| `ccdx source import --file FILE [--select N --apply --key-stdin --yes]` | Preview API metadata; explicitly save one source without client grants |
|
|
14
15
|
| `ccdx source list` / `source add` | List sources or add an API |
|
|
15
16
|
| `ccdx source <id> status` | Read saved account and catalog evidence |
|
|
16
17
|
| `ccdx source <id> models [--refresh]` | Read cached models, or explicitly refresh the source |
|
|
@@ -38,7 +39,7 @@ For installation and first use, start with the [README](../README.md). This refe
|
|
|
38
39
|
| `ccdx config reset --preview` / `restore` | Preview defaults or restore the pre-reset backup |
|
|
39
40
|
| `ccdx requests [--failed] [--active]` | Inspect retained requests |
|
|
40
41
|
| `ccdx requests show <request_id>` | Read one retained request |
|
|
41
|
-
| `ccdx usage [--scope all\|run] [--provider ID] [--model ID] [--days N\|all]` | Read filtered retained usage or current-run totals |
|
|
42
|
+
| `ccdx usage [--scope all\|run] [--provider ID] [--model ID] [--purpose VALUE] [--days N\|all]` | Read filtered retained usage or current-run totals |
|
|
42
43
|
| `ccdx doctor [--online] [--compat] [--fix] [--json]` | Check local setup; optional access checks and repairs |
|
|
43
44
|
| `ccdx doctor config` / `network` / `report` | Read configuration, routing or a redacted local report |
|
|
44
45
|
| `ccdx doctor cache [--limit MiB\|default]` | Inspect runtime buffers or change their limit |
|
|
@@ -68,7 +69,7 @@ inspection. Use `app antigravity status` to check the signed installation explic
|
|
|
68
69
|
The old `app gemini` commands remain available. Authorize Antigravity on the GitHub
|
|
69
70
|
Copilot source page, or with `source github access --edit --apps codex,antigravity --yes`.
|
|
70
71
|
Choose its exposed models on the Antigravity page or with
|
|
71
|
-
`app antigravity models --edit`. Each WebUI
|
|
72
|
+
`app antigravity models --edit`. Each WebUI row represents one model. The Reasoning column lists supported levels as `low / medium / high`, matching Codex and Claude; the model checkbox controls visibility. Save/Discard, refresh, navigation, pausing and an off/on toggle preserve an existing saved route subset. CLI model editing and model files remain available for fine-grained effort selection.
|
|
72
73
|
|
|
73
74
|
The native Gemini catalog still uses distinct routing aliases for each level so its original selector can choose the intended effort. JSON model output retains those aliases for compatibility, with a `model` field identifying the actual model; the management status also includes `model_groups`. A model file accepts `{"models":["gemini-4-carbon"]}` to expose all of its levels, or the existing `ccdx-copilot-...-low|medium|high` aliases to choose a subset.
|
|
74
75
|
After saving, the Antigravity page reports whether the client has fetched the current model list. If the list is pending, reopen Gemini through CCDX.
|
|
@@ -138,6 +139,28 @@ Claude App can continue an existing conversation on another selected, authorized
|
|
|
138
139
|
|
|
139
140
|
Model details show exclusion reasons only when applicable: app/source disabled, source access not granted, missing interface, source restriction, missing catalog entry or no selection. These are configuration/catalog facts, not an online capability test. Expected local GET/HEAD discovery replies are listed separately under Requests → Service probes. Raw HTTP counters remain unchanged; unknown paths, security denials and actual call failures remain inspectable.
|
|
140
141
|
|
|
142
|
+
## Claude capability adaptation
|
|
143
|
+
|
|
144
|
+
On macOS, CCDX reads bounded declarations and their consumers from the installed Claude App. It checks model-list fields, behavior hints, native effort options and maximum-effort handling. Installation changes trigger a coalesced background recheck; the existing refresh cadence also covers missed file events. No application code is executed during inspection and no per-request application scan runs.
|
|
145
|
+
|
|
146
|
+
Verified newer contracts keep stable source-qualified model IDs. Both the native profile and `/v1/models` publish the same behavior hint and maximum effort. Legacy conversation IDs remain accepted. Model order, 1M preferences, manual settings and the existing automatic-sync choice retain their ownership protection. Shared capability maps merge unchanged managed entries and preserve manual entries. A changed native configuration requires a normal Claude restart; CCDX does not interrupt running conversations.
|
|
147
|
+
|
|
148
|
+
Capability declarations, successful synchronization and an observed outgoing effort are separate facts. `ccdx app claude-app status --details`, sync preview and retained request details expose these facts. A missing effort on one request is not proof of missing support. An unverified contract preserves affected existing settings. A non-contiguous set such as low/high/max stays declared and is reported as limited when the native picker cannot express it exactly; CCDX does not invent an intermediate level or silently remap the selection.
|
|
149
|
+
|
|
150
|
+
## API import and request validation
|
|
151
|
+
|
|
152
|
+
**Model sources → Import** and `ccdx source import --file FILE` preview explicitly supplied JSON. Supported shapes are CCDX API metadata/connection exports, CC Switch Claude provider JSON (`settingsConfig.env`), and Magpie `providers.json` with native API bases. Cached deployment evidence, foreign route aliases, account rotation, commands and tool permissions are not adopted. Credential values are not copied; use a private key input or `key_env` when saving. Client access remains a separate explicit choice.
|
|
153
|
+
|
|
154
|
+
The preview reports existing source names/addresses and fields requiring review. **Review draft** opens the existing API editor. The CLI can save one reviewed draft with `--select N --apply --key-stdin --yes`; this grants no app access. Unsupported shapes and mixed-origin endpoints fail validation without writes.
|
|
155
|
+
|
|
156
|
+
Model details can declare `max_tool_definitions` and `supported_parameters`. Catalog parameter lists apply only to their explicitly named protocol. Source input, output and context limits remain separate. Known unsupported parameters, invalid positive-integer output limits and excessive tool definitions fail before dispatch. Unknown metadata remains unknown; CCDX does not guess limits from a model name or remove requested tools.
|
|
157
|
+
|
|
158
|
+
HTTP failures retain a safe technical category, parameter path, reported numeric maximum, source, model, protocol and request ID when available. Unknown vendor explanations remain unknown. Default diagnostics do not copy vendor prose or prompts. HTTP 400 may be a parameter or context rejection; a count-endpoint 404 describes token counting separately.
|
|
159
|
+
|
|
160
|
+
Two confirmed connection failures or temporary 502/503/504 replies trigger a short cooldown for that source interface. The default delay is five seconds; a reported Retry-After can extend it to at most thirty seconds. One later real request checks recovery. Parameter/auth errors, missing token-count endpoints and client cancellation do not trigger it. Other sources and interfaces continue independently. There is no background paid probe or automatic model/account switch.
|
|
161
|
+
|
|
162
|
+
New requests accept the explicit local `X-CCDX-Purpose` value `conversation`, `diagnostic` or `compatibility`; untagged requests are conversations. `doctor --compat` tags its checks as compatibility traffic. Usage and Requests support purpose filters; all purposes remain in default totals. Older usage without a tag stays `unknown` and is not inferred from model names or removed.
|
|
163
|
+
|
|
141
164
|
## Microsoft 365
|
|
142
165
|
|
|
143
166
|
Supported company environments discover local accounts at startup. Access depends on the account, tenant, device policy and service entitlement. Optional failure does not block another source.
|
|
@@ -154,7 +177,7 @@ Catalog diagnostics distinguish local cached data from an online response and ex
|
|
|
154
177
|
- **Request failure:** use Requests or `ccdx requests --failed`. HTTP failures and model completion outcomes are separate. A successful HTTP transport can still carry a model error.
|
|
155
178
|
- **Token counting unavailable:** an observed API count-endpoint 404 is cached briefly per model/header scope. Inference and token counting are separate capabilities; no synthetic count is returned.
|
|
156
179
|
- **Local checks:** `doctor` is read-only by default. `--online` checks access; `--compat` sends minimal inference and consumes usage. `--fix` backs up owned configuration and performs bounded repairs. It does not enable optional features, change company policy or force-restart apps. Partial repairs exit 1.
|
|
157
|
-
- **App updates:** after the service is ready, CCDX observes installed App versions in the background. Checks & repairs shows the result; `ccdx doctor` can inspect it locally. On macOS this uses known App bundle metadata and, when available, the bundled Codex CLI version. On Windows the registered Codex package is inspected; Claude App remains unknown if reliable metadata is unavailable. The running process may still be an older build, and a version observation does not verify images, predictions, model access or protocol compatibility.
|
|
180
|
+
- **App updates:** after the service is ready, CCDX observes installed App versions in the background. Checks & repairs shows the result; `ccdx doctor` can inspect it locally. On macOS this includes Antigravity (the original Gemini App) and uses known App bundle metadata and, when available, the bundled Codex CLI version. On Windows the registered Codex package is inspected; Claude App remains unknown if reliable metadata is unavailable. The running process may still be an older build, and a version observation does not verify images, predictions, model access or protocol compatibility. Claude capability synchronization uses the installed macOS App contract described below. An installed version alone does not establish native adoption. The compact local version record contains only App versions, builds and observation times, not credentials or conversation data. It is refreshed on startup, local checks and the existing model-refresh cadence; a reused service receives a nonblocking refresh notification.
|
|
158
181
|
- **Cache cleanup:** adding `--history` can break the next continuation. It does not delete client transcripts or generated images.
|
|
159
182
|
|
|
160
183
|
Request inspection covers bounded retained records, not a full conversation archive. Unidentified clients stay unidentified. Routine diagnostics omit secrets, prompts and error bodies. Explicit error excerpts use bounded, redacted collection. The usage JSON `requests` field counts recorded usage rows, not HTTP calls. Usage is returned token metadata; cache hit is reused input divided by input from records with valid counts for both. Unknown/invalid records remain in token totals but are excluded from both sides of the rate, with partial coverage indicated. It is not a request-based cache rate or a billing receipt.
|
|
@@ -165,12 +188,13 @@ Native records use source `google`; Copilot records use `github`. Google output
|
|
|
165
188
|
|
|
166
189
|
Requests and usage share the CCDX request ID; an upstream response ID is separate. Request details show the original model when it differs from the actual model, and distinguish reported, partial, missing and unreadable usage metadata. Requests waiting for body parsing show “Model pending” and “Source pending”; queue, input processing, upstream wait and response delivery have separate states. The CLI exposes the same retained metadata with `ccdx requests show ID --format json`; `ccdx requests --app antigravity` filters the native integration.
|
|
167
190
|
|
|
168
|
-
Usage source, model and time controls apply to the entire token-usage page: totals, model rows and charts. Selecting a day narrows that shared query; Clear date restores the previous period. Chart type, language and theme changes remain local. All retained history remains available; date charts keep at most 365 daily points and combine earlier valid records into an Earlier records bucket. Invalid/future timestamps remain in all-history totals but are excluded from date charts and bounded date filters, with the exclusion count shown. Model choices are bounded to 100 and preserve other available choices while a filter is active.
|
|
191
|
+
Usage source, model, purpose and time controls apply to the entire token-usage page: totals, model rows and charts. Selecting a day narrows that shared query; Clear date restores the previous period. Chart type, language and theme changes remain local. All retained history remains available; date charts keep at most 365 daily points and combine earlier valid records into an Earlier records bucket. Invalid/future timestamps remain in all-history totals but are excluded from date charts and bounded date filters, with the exclusion count shown. Model choices are bounded to 100 and preserve other available choices while a filter is active.
|
|
169
192
|
|
|
170
193
|
CLI and TUI subcommands share the same source/model/calendar semantics:
|
|
171
194
|
|
|
172
195
|
```sh
|
|
173
196
|
ccdx usage --provider google --days 7
|
|
197
|
+
ccdx usage --purpose diagnostic
|
|
174
198
|
ccdx usage --model 'github / gemini-4-carbon' --from 2026-11-01 --to 2026-11-13 --time-zone Asia/Shanghai
|
|
175
199
|
ccdx usage --scope run --provider google
|
|
176
200
|
ccdx requests --app antigravity --active
|
package/package.json
CHANGED
package/src/adapter.mjs
CHANGED
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
createRequestMetrics,
|
|
12
12
|
runtimeStatusPayload,
|
|
13
13
|
} from "./observability.mjs";
|
|
14
|
-
import { createRequestId, runWithRequestContext, currentRequestContext } from "./request-context.mjs";
|
|
14
|
+
import { createRequestId, runWithRequestContext, currentRequestContext, requestPurpose } from "./request-context.mjs";
|
|
15
15
|
import { requestApplication } from "./request-application.mjs";
|
|
16
16
|
import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
|
|
17
17
|
import { createLocalPrivacy } from "./local-privacy.mjs";
|
|
@@ -480,7 +480,8 @@ export function createAdapterHandler(options = {}) {
|
|
|
480
480
|
&& !DASHBOARD_API_PATHS.has(pathname)
|
|
481
481
|
&& !((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname));
|
|
482
482
|
const complete = trackRequest ? requestMetrics.begin(routeName) : () => {};
|
|
483
|
-
const
|
|
483
|
+
const purpose = requestPurpose(req.headers["x-ccdx-purpose"]);
|
|
484
|
+
const streamPerformance = trackRequest && !isDiscoveryRequest(req.method, pathname) ? streamPerformanceMetrics.begin(routeName, { requestId, purpose, application: requestApplication(req.headers, routeName === "antigravity" ? "gemini_app" : "api") }) : null;
|
|
484
485
|
let finishTerminalActivity = () => {};
|
|
485
486
|
if (trackRequest && !isDiscoveryRequest(req.method, pathname) && ["responses", "responses_compact", "messages", "images", "image_mcp", "search", "antigravity"].includes(routeName)) {
|
|
486
487
|
try {
|
|
@@ -538,6 +539,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
538
539
|
try {
|
|
539
540
|
context = {
|
|
540
541
|
requestId,
|
|
542
|
+
purpose,
|
|
541
543
|
pathname,
|
|
542
544
|
showRequestId: options.showRequestId === true,
|
|
543
545
|
includeHttpErrorDetails: options.includeHttpErrorDetails === true || process.env.CCDX_HTTP_ERROR_DETAILS === "1",
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { watch } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { readBoundedFile } from "./bounded-file.mjs";
|
|
6
|
+
|
|
7
|
+
const MAX_HEADER = 4 * 1024 * 1024, MAX_SOURCE = 16 * 1024 * 1024;
|
|
8
|
+
const cache = new Map();
|
|
9
|
+
const version = text => /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(text)?.[1];
|
|
10
|
+
const stamp = stat => [stat.dev, stat.ino, stat.size, stat.mtimeMs].join(":");
|
|
11
|
+
|
|
12
|
+
export function watchClaudeAppContract({ platform = process.platform, appPath = "/Applications/Claude.app", onChange = () => {}, watchFile = watch } = {}) {
|
|
13
|
+
const watchers = [];let timer, closed = false;
|
|
14
|
+
const schedule = () => {
|
|
15
|
+
clearTimeout(timer);
|
|
16
|
+
timer = setTimeout(() => { if (!closed) void Promise.resolve().then(onChange).catch(() => {}); }, 250);timer.unref?.();
|
|
17
|
+
};
|
|
18
|
+
if (platform === "darwin") for (const [directory, name] of [[path.dirname(appPath), path.basename(appPath)], [path.join(appPath, "Contents"), "Info.plist"], [path.join(appPath, "Contents", "Resources"), "app.asar"]]) {
|
|
19
|
+
try {
|
|
20
|
+
const watcher = watchFile(directory, { persistent: false }, (_event, file) => { if (!file || String(file) === name) schedule(); });
|
|
21
|
+
watcher.on("error", () => watcher.close());watchers.push(watcher);
|
|
22
|
+
} catch { /* Existing periodic inspection also covers replacement/watch failure. */ }
|
|
23
|
+
}
|
|
24
|
+
return { close() { closed = true;clearTimeout(timer);for (const watcher of watchers) watcher.close(); } };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function archiveFiles(node, prefix = "", output = []) {
|
|
28
|
+
for (const [name, entry] of Object.entries(node.files || {})) {
|
|
29
|
+
const file = prefix + name;
|
|
30
|
+
if (entry.files) archiveFiles(entry, file + "/", output);
|
|
31
|
+
else if (!entry.unpacked && Number.isSafeInteger(entry.size) && /^\d+$/.test(entry.offset || "")) output.push({ name: file, ...entry });
|
|
32
|
+
}
|
|
33
|
+
return output;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Read declarations and their consumers, not a release-number allowlist.
|
|
37
|
+
// No application code is executed and no user profile or credential is read.
|
|
38
|
+
export function parseClaudeAppContract(source) {
|
|
39
|
+
const profiles = [];
|
|
40
|
+
for (const match of source.matchAll(/"(claude-[a-z]+-[0-9][0-9.-]*)":\{effortLevels:\[([^\]]{0,120})\]/g)) {
|
|
41
|
+
const values = match[2].match(/"(?:low|medium|high|xhigh|max)"/g)?.map(value => JSON.parse(value));
|
|
42
|
+
if (values?.length && values.join(",") === match[2].replaceAll('"', "").replaceAll(" ", "") && new Set(values).size === values.length)
|
|
43
|
+
profiles.push({ model: match[1], efforts: values });
|
|
44
|
+
}
|
|
45
|
+
const fields = {
|
|
46
|
+
models: /flatKey:"inferenceModels"/.test(source) && /readers:\["desktop","m365","code"\]/.test(source),
|
|
47
|
+
discovery: /flatKey:"modelDiscoveryEnabled"/.test(source),
|
|
48
|
+
behaves_as: /\.find\(\(\w+=>\w+\.behavesAs\)\)\?\.behavesAs/.test(source),
|
|
49
|
+
effort_cap: /maxEffortLevel/.test(source) && /\.effort_options/.test(source) && /\.maxEffort/.test(source),
|
|
50
|
+
context: /autoCompactWindow/.test(source) && /1000000/.test(source),
|
|
51
|
+
output: /CLAUDE_CODE_MAX_OUTPUT_TOKENS/.test(source),
|
|
52
|
+
};
|
|
53
|
+
const picker = profiles.length > 0 && fields.models && fields.behaves_as && fields.effort_cap;
|
|
54
|
+
const facts = { fields, profiles: profiles.sort((a, b) => a.model.localeCompare(b.model)) };
|
|
55
|
+
return { status: picker ? "verified" : "unverified", ...facts,
|
|
56
|
+
fingerprint: createHash("sha256").update(JSON.stringify(facts)).digest("hex").slice(0, 24) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function inspectClaudeAppContract({ platform = process.platform, appPath = "/Applications/Claude.app", appSource } = {}) {
|
|
60
|
+
if (typeof appSource === "string") return parseClaudeAppContract(appSource);
|
|
61
|
+
if (platform !== "darwin") return { status: "unavailable", fields: {}, profiles: [], fingerprint: null };
|
|
62
|
+
const archive = path.join(appPath, "Contents", "Resources", "app.asar");let handle;
|
|
63
|
+
try {
|
|
64
|
+
const info = await readBoundedFile(path.join(appPath, "Contents", "Info.plist"), { maxBytes: 65536, encoding: "utf8" });
|
|
65
|
+
if (!/<key>CFBundleIdentifier<\/key>\s*<string>com\.anthropic\.claudefordesktop<\/string>/.test(info)) throw Error("Unrecognized App");
|
|
66
|
+
const before = await fs.stat(archive), key = stamp(before), previous = cache.get(archive);
|
|
67
|
+
if (previous?.key === key) return { ...structuredClone(previous.value), app_version: version(info) || null };
|
|
68
|
+
handle = await fs.open(archive, "r");const prefix = Buffer.alloc(16);await handle.read(prefix, 0, 16, 0);
|
|
69
|
+
const headerSize = prefix.readUInt32LE(12), base = 8 + prefix.readUInt32LE(4);
|
|
70
|
+
if (headerSize <= 0 || headerSize > MAX_HEADER || base > before.size) throw Error("Invalid archive");
|
|
71
|
+
const header = Buffer.alloc(headerSize);await handle.read(header, 0, headerSize, 16);
|
|
72
|
+
const files = archiveFiles(JSON.parse(header.toString("utf8"))).filter(file => /^\.vite\/build\/index(?:\.chunk[^/]*|\.pre)\.js$/.test(file.name)
|
|
73
|
+
&& file.size > 500000 && file.size <= MAX_SOURCE).sort((a, b) => b.size - a.size);
|
|
74
|
+
let result = { status: "unverified", fields: {}, profiles: [], fingerprint: null };
|
|
75
|
+
for (const file of files.slice(0, 6)) {
|
|
76
|
+
const offset = base + Number(file.offset);if (!Number.isSafeInteger(offset) || offset + file.size > before.size) continue;
|
|
77
|
+
const bytes = Buffer.alloc(file.size);await handle.read(bytes, 0, bytes.length, offset);
|
|
78
|
+
const candidate = parseClaudeAppContract(bytes.toString("utf8"));
|
|
79
|
+
if (candidate.status === "verified") { result = candidate;break; }
|
|
80
|
+
}
|
|
81
|
+
if (stamp(await fs.stat(archive)) !== key) throw Error("App changed during inspection");
|
|
82
|
+
const value = { ...result, app_version: version(info) || null, installation: key };
|
|
83
|
+
cache.set(archive, { key, value });if (cache.size > 2) cache.delete(cache.keys().next().value);
|
|
84
|
+
return structuredClone(value);
|
|
85
|
+
} catch { return { status: "unavailable", fields: {}, profiles: [], fingerprint: null }; }
|
|
86
|
+
finally { await handle?.close(); }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function claudeNativeModelHint(values = {}, contract) {
|
|
90
|
+
if (contract?.status !== "verified" || values.reasoning === false) return null;
|
|
91
|
+
const levels = values.reasoning_efforts || [], order = ["low", "medium", "high", "xhigh", "max"];
|
|
92
|
+
if (!levels.length || levels.some(level => !order.includes(level))) return null;
|
|
93
|
+
const sorted = order.filter(level => levels.includes(level)), maximum = sorted.at(-1);
|
|
94
|
+
const profile = contract.profiles?.find(profile => profile.efforts.filter(level => order.indexOf(level) <= order.indexOf(maximum)).join(",") === sorted.join(","));
|
|
95
|
+
return profile ? { behavesAs: profile.model, maxEffort: maximum } : null;
|
|
96
|
+
}
|
|
@@ -5,8 +5,10 @@ import { m365Paths, readM365Json } from "./m365-settings.mjs";
|
|
|
5
5
|
import { claudeEffortsExpressible, claudeEffortPrefix } from "./model-capabilities.mjs";
|
|
6
6
|
import { claudeModelEntries } from "./claude-models.mjs";
|
|
7
7
|
import { claudeClientPaths, reconcileClaudeConfiguration } from "./claude-client-config.mjs";
|
|
8
|
+
import { claudeNativeModelHint } from "./claude-app-contract.mjs";
|
|
9
|
+
import { claudeRouteAliases } from "./clients/claude-models.mjs";
|
|
8
10
|
|
|
9
|
-
export function inspectClaudeCapabilitySupport({ platform = process.platform, env = process.env, appVersion, codeVersion } = {}) {
|
|
11
|
+
export function inspectClaudeCapabilitySupport({ platform = process.platform, env = process.env, appVersion, codeVersion, appContract } = {}) {
|
|
10
12
|
if (!codeVersion) for (const directory of (env.PATH || "").split(path.delimiter).filter(Boolean)) {
|
|
11
13
|
try {
|
|
12
14
|
const executable = fs.realpathSync(path.join(directory, platform === "win32" ? "claude.exe" : "claude"));
|
|
@@ -23,22 +25,26 @@ export function inspectClaudeCapabilitySupport({ platform = process.platform, en
|
|
|
23
25
|
}
|
|
24
26
|
// The 3.x and 4.x App schema/host were independently inspected. Other versions keep
|
|
25
27
|
// working catalogs without claiming adoption of undocumented host controls.
|
|
26
|
-
|
|
28
|
+
const verified = appContract?.status === "verified";
|
|
29
|
+
return { app_version: appContract?.app_version || appVersion || null, app: verified || /^[34]\./.test(appVersion || ""),
|
|
30
|
+
app_aliases: !verified, ...(appContract ? { app_contract: appContract } : {}),
|
|
31
|
+
code_version: codeVersion || null, code: /^2\.1\./.test(codeVersion || "") && Number(codeVersion.split(".")[2]) >= 293 };
|
|
27
32
|
}
|
|
28
33
|
|
|
29
34
|
export function claudeSupportForSync(support, observations) {
|
|
30
35
|
const rows = Array.isArray(observations?.claude) ? observations.claude : [];
|
|
31
36
|
const app = rows.find(entry => entry.id === "claude_system_claude");
|
|
37
|
+
if (support.app_contract?.status === "verified" && (!app?.version || app.version === support.app_version)) return support;
|
|
32
38
|
return observations?.claude_unrecognized === true || app?.version && !/^[34]\./.test(app.version) ? { ...support, app: false } : support;
|
|
33
39
|
}
|
|
34
40
|
|
|
35
41
|
export function claudeSharedCapabilityPlan({ app = [], code = [], support = {} } = {}) {
|
|
36
|
-
const limitations = [], budgets = {}, caps = [], consumers = [...app.map(model => ({ model, app: true })), ...code.map(model => ({ model, app: false }))];
|
|
42
|
+
const limitations = [], budgets = {}, caps = [], preserveRefs = [], consumers = [...app.map(model => ({ model, app: true })), ...code.map(model => ({ model, app: false }))];
|
|
37
43
|
let context = 0, output = 0, safeContext = consumers.length > 0, knownAdapters = true;
|
|
38
44
|
for (const { model, app: desktop } of consumers) {
|
|
39
45
|
const entry = claudeModelEntries([model], { desktopAliases: desktop })[0], values = model.capability?.values || {};
|
|
40
46
|
const id = model.public_id || entry.name;
|
|
41
|
-
if (desktop ? !support.app : !support.code) { safeContext = false;knownAdapters = false;limitations.push({ model: model.id, code: "client_version_unknown" });continue; }
|
|
47
|
+
if (desktop ? !support.app : !support.code) { safeContext = false;knownAdapters = false;limitations.push({ model: model.id, code: "client_version_unknown" });preserveRefs.push(id, ...(model.route_id ? claudeRouteAliases(model, model.route_id, desktop) : []));continue; }
|
|
42
48
|
const window = values.context_window;
|
|
43
49
|
if (!window) { safeContext = false;limitations.push({ model: model.id, code: "context_unknown" }); }
|
|
44
50
|
else if (window < 100000 || window > 1000000) { safeContext = false;limitations.push({ model: model.id, code: "context_range_limited", value: window }); }
|
|
@@ -46,21 +52,26 @@ export function claudeSharedCapabilityPlan({ app = [], code = [], support = {} }
|
|
|
46
52
|
if (budgets[id] && budgets[id] < 100000) { safeContext = false;delete budgets[id];limitations.push({ model: model.id, code: "context_range_limited" }); }
|
|
47
53
|
output = Math.max(output, values.max_output_tokens || 0);
|
|
48
54
|
const efforts = values.reasoning === false ? [] : values.reasoning_efforts || [];
|
|
49
|
-
|
|
50
|
-
const
|
|
55
|
+
const hint = desktop ? claudeNativeModelHint(values, support.app_contract) : null;
|
|
56
|
+
const limited=desktop&&/^mythos-ccdx-\d+$/.test(id)?claudeEffortPrefix(values).length!==efforts.length:!claudeEffortsExpressible(values);
|
|
57
|
+
if (efforts.length && !hint && limited) limitations.push({ model: model.id, code: "reasoning_levels_limited" });
|
|
58
|
+
const visibleEfforts = hint ? efforts : desktop && /^mythos-ccdx-\d+$/.test(id) ? claudeEffortPrefix(values) : claudeEffortsExpressible(values) ? efforts : [];
|
|
51
59
|
if (visibleEfforts.length) caps.push(`${id.toLowerCase()}=${["effort", ...(visibleEfforts.includes("xhigh") ? ["xhigh_effort"] : []), ...(visibleEfforts.includes("max") ? ["max_effort"] : [])].join(",")}`);
|
|
60
|
+
else if(efforts.length)preserveRefs.push(id,...(model.route_id?claudeRouteAliases(model,model.route_id,desktop):[]));
|
|
52
61
|
if (values.web_search && !values.web_search.includes("messages")) limitations.push({ model: model.id, code: "search_messages_unavailable" });
|
|
53
62
|
}
|
|
54
63
|
if (!safeContext) context = 0;
|
|
55
64
|
const capabilities = caps.join(";");
|
|
56
65
|
if (capabilities.length > 8000) limitations.push({ code: "capability_list_limited" });
|
|
57
66
|
return { state: consumers.length ? "planned" : "not_configured", context_tokens: context || null,
|
|
58
|
-
|
|
67
|
+
preserve_refs: preserveRefs,
|
|
68
|
+
preserve_fields: [...(!knownAdapters ? ["env.CLAUDE_CODE_MAX_CONTEXT_TOKENS"] : []), ...(!knownAdapters || support.app_contract && !support.app_contract.fields.output ? ["env.CLAUDE_CODE_MAX_OUTPUT_TOKENS"] : [])],
|
|
69
|
+
output_tokens: output && knownAdapters && (!support.app_contract || support.app_contract.fields.output) && consumers.every(({ model }) => model.capability?.values.max_output_tokens) ? Math.min(output, 128000) : null, budgets: context ? budgets : {},
|
|
59
70
|
capabilities: capabilities.length <= 8000 ? capabilities : "", limitations };
|
|
60
71
|
}
|
|
61
72
|
|
|
62
73
|
export function syncClaudeCapabilities(plan, options = {}) {
|
|
63
|
-
if (plan.limitations?.some(item => item.code === "client_version_unknown")) return { state: "partially_preserved", changed: false, preserved: 0, restart_required: false };
|
|
74
|
+
if (plan.limitations?.some(item => item.code === "client_version_unknown") && !plan.capabilities) return { state: "partially_preserved", changed: false, preserved: 0, restart_required: false };
|
|
64
75
|
const paths = claudeClientPaths(options), env = options.env || process.env;
|
|
65
76
|
let current = {};try { current = JSON.parse(readBoundedFileSync(paths.code, { maxBytes: 1024 * 1024, encoding: "utf8" })); }
|
|
66
77
|
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
@@ -74,13 +85,18 @@ export function syncClaudeCapabilities(plan, options = {}) {
|
|
|
74
85
|
const ownedFields = ["env.CLAUDE_CODE_MAX_CONTEXT_TOKENS", "env.CLAUDE_CODE_MAX_OUTPUT_TOKENS", "env.CLAUDE_CODE_MODEL_CAPABILITIES"];
|
|
75
86
|
if (!conflict) {
|
|
76
87
|
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]]) {
|
|
77
|
-
|
|
88
|
+
let selected=value;
|
|
89
|
+
if(key==="CLAUDE_CODE_MODEL_CAPABILITIES"&&selected){
|
|
90
|
+
const keep=new Set(plan.preserve_refs||[]),previous=String(current.env?.[key]||"").split(";").filter(item=>keep.has(item.split("=")[0]));
|
|
91
|
+
selected=[selected,...previous].join(";");
|
|
92
|
+
}
|
|
93
|
+
if (selected && env[key] === undefined) operations.push({file:paths.code,keys:["env",key],value:String(selected),...(key==="CLAUDE_CODE_MODEL_CAPABILITIES"?{mergeCapabilities:true}:{})});
|
|
78
94
|
}
|
|
79
95
|
for (const [id, value] of Object.entries(plan.budgets)) add(["modelSettings", id, "autoCompactWindow"], value);
|
|
80
96
|
}
|
|
81
97
|
const active = new Set(operations.map(op => op.keys.join(".")));
|
|
82
98
|
const result = reconcileClaudeConfiguration(operations, { ...options,
|
|
83
|
-
restoreSelect: op => op.file === paths.code && (ownedFields.includes(op.keys.join(".")) || op.keys[0] === "modelSettings" && op.keys[2] === "autoCompactWindow") && !active.has(op.keys.join(".")) });
|
|
99
|
+
restoreSelect: op => op.file === paths.code && !plan.preserve_fields?.includes(op.keys.join(".")) && !plan.preserve_refs?.includes(op.keys[1]) && (ownedFields.includes(op.keys.join(".")) || op.keys[0] === "modelSettings" && op.keys[2] === "autoCompactWindow") && !active.has(op.keys.join(".")) });
|
|
84
100
|
return { state: conflict || result.preserved ? "partially_preserved" : operations.length ? "configured" : "limited",
|
|
85
101
|
changed: result.changed, preserved: result.preserved,
|
|
86
102
|
restart_required: result.changed };
|
|
@@ -10,6 +10,7 @@ import { withFileLockSync } from "./lock.mjs";
|
|
|
10
10
|
import { m365Paths, readM365Json, writeM365Json } from "./m365-settings.mjs";
|
|
11
11
|
import { claudeClientModelId, claudeModelEntries } from "./claude-models.mjs";
|
|
12
12
|
import { claudeRouteAliases } from "./clients/claude-models.mjs";
|
|
13
|
+
import { claudeNativeModelHint } from "./claude-app-contract.mjs";
|
|
13
14
|
|
|
14
15
|
export const M365_CLAUDE_PROFILE_ID = "00000000-0000-4000-8000-000000202700";
|
|
15
16
|
const M365_CLAUDE_PROFILE_NAME = "CCDX Microsoft 365";
|
|
@@ -115,6 +116,42 @@ function appModelsOwned(current, previous, desired, alreadyDesired) {
|
|
|
115
116
|
withoutAppPreference(recorded.filter(model => wanted.has(model.name))));
|
|
116
117
|
}
|
|
117
118
|
|
|
119
|
+
function capabilityMap(value){
|
|
120
|
+
if(typeof value!=="string")return null;const result=new Map();
|
|
121
|
+
for(const entry of value.split(";").filter(Boolean)){
|
|
122
|
+
const [id,flags,...extra]=entry.split("=");
|
|
123
|
+
if(extra.length||!/^[\w][\w./:@+\[\]-]{0,200}$/.test(id)||!flags||flags.split(",").some(flag=>!["effort","xhigh_effort","max_effort"].includes(flag))||result.has(id))return null;
|
|
124
|
+
result.set(id,flags);
|
|
125
|
+
}
|
|
126
|
+
return result;
|
|
127
|
+
}
|
|
128
|
+
const capabilityText = map => [...map].map(([id, flags]) => id + "=" + flags).join(";");
|
|
129
|
+
function mergeCapabilityMap(current, recorded, wanted, original) {
|
|
130
|
+
const actual = capabilityMap(current ?? ""), previous = capabilityMap(recorded), next = capabilityMap(wanted), before = capabilityMap(original?.value ?? "");
|
|
131
|
+
if (!actual || !previous || !next || !before) return null;
|
|
132
|
+
const result = new Map(actual), restoration = new Map(before);let preserved = false;
|
|
133
|
+
for (const id of new Set([...previous.keys(), ...actual.keys()])) if (actual.get(id) !== previous.get(id)) {
|
|
134
|
+
if (actual.has(id)) restoration.set(id, actual.get(id));else restoration.delete(id);
|
|
135
|
+
}
|
|
136
|
+
for (const [id, flags] of previous) if (actual.get(id) === flags && flags !== before.get(id) && !next.has(id)) result.delete(id);
|
|
137
|
+
for (const [id, flags] of next) {
|
|
138
|
+
if (actual.has(id) && actual.get(id) !== flags && (actual.get(id) !== previous.get(id) || actual.get(id) === before.get(id))) { preserved = true;continue; }
|
|
139
|
+
result.set(id, flags);
|
|
140
|
+
}
|
|
141
|
+
return { value: capabilityText(result), before: restoration.size || original?.exists ? { exists: true, value: capabilityText(restoration) } : { exists: false }, preserved };
|
|
142
|
+
}
|
|
143
|
+
function restoreCapabilityMap(current, operation) {
|
|
144
|
+
const actual = capabilityMap(current.value ?? ""), after = capabilityMap(operation.after), before = capabilityMap(operation.before?.value ?? "");
|
|
145
|
+
if (!actual || !after || !before) return null;
|
|
146
|
+
const result = new Map(actual);let preserved = false;
|
|
147
|
+
for (const [id, flags] of after) {
|
|
148
|
+
if (flags === before.get(id)) continue;
|
|
149
|
+
if (actual.get(id) !== flags) { preserved = true;continue; }
|
|
150
|
+
if (before.has(id)) result.set(id, before.get(id));else result.delete(id);
|
|
151
|
+
}
|
|
152
|
+
return { desired: result.size || operation.before?.exists ? { exists: true, value: capabilityText(result) } : { exists: false }, preserved };
|
|
153
|
+
}
|
|
154
|
+
|
|
118
155
|
export function reconcileClaudeConfiguration(operations, { restore = false, restoreFields = [], restoreSelect, ...options } = {}) {
|
|
119
156
|
const paths = claudeClientPaths(options), allowed = new Set(Object.values(paths)), journalPath = m365Paths(options).ownership;
|
|
120
157
|
fs.mkdirSync(path.dirname(journalPath), { recursive: true, mode: 0o700 });
|
|
@@ -124,7 +161,7 @@ export function reconcileClaudeConfiguration(operations, { restore = false, rest
|
|
|
124
161
|
[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"])],
|
|
125
162
|
[paths.normal, new Set(["deploymentMode"])], [paths.threep, new Set(["deploymentMode"])],
|
|
126
163
|
[paths.meta, new Set(["entries", "appliedId"])],
|
|
127
|
-
[paths.profile, new Set(["inferenceProvider", "inferenceGatewayBaseUrl", "inferenceGatewayApiKey", "inferenceGatewayAuthScheme", "inferenceModels", "inferenceCustomHeaders"])],
|
|
164
|
+
[paths.profile, new Set(["inferenceProvider", "inferenceGatewayBaseUrl", "inferenceGatewayApiKey", "inferenceGatewayAuthScheme", "inferenceModels", "inferenceCustomHeaders", "modelDiscoveryEnabled"])],
|
|
128
165
|
]);
|
|
129
166
|
const safeKeys = op => Array.isArray(op.keys) && !op.keys.some(key => ["__proto__", "constructor", "prototype"].includes(key))
|
|
130
167
|
&& (keys.get(op.file)?.has(op.keys.join(".")) || op.file === paths.code && op.keys.length === 3 && op.keys[0] === "modelSettings"
|
|
@@ -146,19 +183,27 @@ export function reconcileClaudeConfiguration(operations, { restore = false, rest
|
|
|
146
183
|
const state = states.get(operation.file);state.next ||= structuredClone(state.value);
|
|
147
184
|
const previous = journal.operations.find(op => op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId);
|
|
148
185
|
const restoring = restore || operation.restore === true;
|
|
149
|
-
const current = operationValue(state.next, operation)
|
|
186
|
+
const current = operationValue(state.next, operation);let desired = restoring ? operation.before : { exists: true, value: operation.value };
|
|
187
|
+
const capabilityField = operation.file === paths.code && operation.keys.join(".") === "env.CLAUDE_CODE_MODEL_CAPABILITIES";
|
|
150
188
|
if (restoring) {
|
|
151
|
-
|
|
189
|
+
const capabilityRestore = capabilityField ? restoreCapabilityMap(current, operation) : null;
|
|
190
|
+
if (capabilityRestore) { desired = capabilityRestore.desired;if (capabilityRestore.preserved) skipped.push(operation.file); }
|
|
191
|
+
else if (!isDeepStrictEqual(current, { exists: true, value: operation.after })) { skipped.push(operation.file);continue; }
|
|
152
192
|
setOperation(state.next, operation, desired);
|
|
153
193
|
nextJournal.operations = nextJournal.operations.filter(op => !(op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId));
|
|
154
194
|
} else {
|
|
195
|
+
const capabilityMerge = operation.mergeCapabilities && previous && capabilityField
|
|
196
|
+
? mergeCapabilityMap(current.value, previous.after, desired.value, previous.before) : null;
|
|
197
|
+
if(capabilityMerge){desired.value=capabilityMerge.value;operation.value=capabilityMerge.value;if(capabilityMerge.preserved)skipped.push(operation.file)}
|
|
155
198
|
const modelField = operation.file === paths.profile && operation.keys.join(".") === "inferenceModels";
|
|
156
199
|
const currentModels = modelField && parsedAppModels(current.value), desiredModels = modelField && parsedAppModels(desired.value);
|
|
157
200
|
const alreadyDesired = isDeepStrictEqual(current, desired)
|
|
158
201
|
|| Boolean(currentModels && desiredModels && isDeepStrictEqual(currentModels, desiredModels));
|
|
159
|
-
const owned = previous && (isDeepStrictEqual(current, { exists: true, value: previous.after })
|
|
202
|
+
const owned = previous && (Boolean(capabilityMerge)||isDeepStrictEqual(current, { exists: true, value: previous.after })
|
|
160
203
|
|| modelField && current.exists && appModelsOwned(current.value, previous.after, desired.value, alreadyDesired));
|
|
161
204
|
if (alreadyDesired) {
|
|
205
|
+
if (capabilityMerge) nextJournal.operations = nextJournal.operations.map(op => op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys)
|
|
206
|
+
? { ...op, before: capabilityMerge.before, after: current.value } : op);
|
|
162
207
|
if (modelField && owned && previous.after !== current.value) {
|
|
163
208
|
nextJournal.operations = nextJournal.operations.map(op => op.file === operation.file
|
|
164
209
|
&& isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId ? { ...op, after: current.value } : op);
|
|
@@ -169,7 +214,7 @@ export function reconcileClaudeConfiguration(operations, { restore = false, rest
|
|
|
169
214
|
&& current.value === "1p";
|
|
170
215
|
if (current.exists && !replaceMode && !owned) { skipped.push(operation.file);continue; }
|
|
171
216
|
const entry = { file: operation.file, keys: operation.keys, ...(operation.itemId ? { itemId: operation.itemId } : {}),
|
|
172
|
-
before: previous?.before || current, after: operation.value };
|
|
217
|
+
before: capabilityMerge?.before || previous?.before || current, after: operation.value };
|
|
173
218
|
setOperation(state.next, operation, desired);
|
|
174
219
|
nextJournal.operations = nextJournal.operations.filter(op => !(op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId));
|
|
175
220
|
nextJournal.operations.push(entry);
|
|
@@ -200,7 +245,7 @@ export function reconcileClaudeConfiguration(operations, { restore = false, rest
|
|
|
200
245
|
});
|
|
201
246
|
}
|
|
202
247
|
|
|
203
|
-
export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, desktopAliases = false, profileName = M365_CLAUDE_PROFILE_NAME, disableExperimentalBetas = true, defaultModel, ...options } = {}) {
|
|
248
|
+
export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, desktopAliases = false, appContract, profileName = M365_CLAUDE_PROFILE_NAME, disableExperimentalBetas = true, defaultModel, ...options } = {}) {
|
|
204
249
|
const entries = claudeModelEntries(models);
|
|
205
250
|
const paths = claudeClientPaths(options), ids = entries.map(model => model.name), operations = [], result = {};
|
|
206
251
|
const endpoint = new URL(baseUrl);
|
|
@@ -270,7 +315,10 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
|
|
|
270
315
|
const previousNames = models.map(model => model.route_id ? claudeRouteAliases(model, model.route_id, true).slice(2) : []);
|
|
271
316
|
const desktopEntries = (desktopAliases ? claudeModelEntries(models, { desktopAliases }) : entries).map((entry, index) => {
|
|
272
317
|
const previous = previousByName.get(entry.name) || previousNames[index].map(name => previousByName.get(name)).find(Boolean);
|
|
273
|
-
|
|
318
|
+
const hint = claudeNativeModelHint(models[index].capability?.values, appContract);
|
|
319
|
+
const controls = hint || (appContract && appContract.status !== "verified" && previous?.behavesAs && models[index].capability?.values.reasoning !== false
|
|
320
|
+
? { behavesAs: previous.behavesAs, ...(entry.maxEffort === undefined && previous.maxEffort ? { maxEffort: previous.maxEffort } : {}) } : {});
|
|
321
|
+
return { ...entry, ...controls, ...(entry.supports1m ? { prefer1m: typeof previous?.prefer1m === "boolean" ? previous.prefer1m : true } : {}) };
|
|
274
322
|
});
|
|
275
323
|
for (let index = 0; index < models.length; index++) {
|
|
276
324
|
const old = previousNames[index].map(name => order.get(name)).find(value => value !== undefined) ?? order.get(claudeClientModelId(models[index].id));
|
|
@@ -279,6 +327,7 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
|
|
|
279
327
|
const orderedEntries = [...desktopEntries].sort((left, right) => defaultModel && (left.name === defaultModel || right.name === defaultModel)
|
|
280
328
|
? left.name === defaultModel ? -1 : 1 : (order.get(left.name) ?? Infinity) - (order.get(right.name) ?? Infinity));
|
|
281
329
|
add(paths.profile, ["inferenceModels"], JSON.stringify(orderedEntries));
|
|
330
|
+
if(appContract?.fields.discovery)add(paths.profile,["modelDiscoveryEnabled"],true);
|
|
282
331
|
add(paths.profile, ["inferenceCustomHeaders"], JSON.stringify({ "X-CCDX-Client": "claude-app" }));
|
|
283
332
|
add(paths.meta, ["entries"], { id: M365_CLAUDE_PROFILE_ID, name: profileName }, M365_CLAUDE_PROFILE_ID);
|
|
284
333
|
add(paths.meta, ["appliedId"], M365_CLAUDE_PROFILE_ID);
|