codex-copilot-dx 1.3.27 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +7 -2
  2. package/bin/cli.mjs +4 -1
  3. package/docs/ARCHITECTURE.md +32 -3
  4. package/docs/REFERENCE.md +51 -5
  5. package/package.json +1 -1
  6. package/src/adapter.mjs +17 -5
  7. package/src/antigravity-handler.mjs +38 -13
  8. package/src/antigravity-runtime.mjs +22 -2
  9. package/src/claude-app-contract.mjs +96 -0
  10. package/src/claude-capability-config.mjs +28 -11
  11. package/src/claude-client-config.mjs +58 -9
  12. package/src/claude-gateway.mjs +25 -7
  13. package/src/claude-models.mjs +4 -2
  14. package/src/cli-command-spec.mjs +13 -3
  15. package/src/cli-management.mjs +47 -6
  16. package/src/cli-options.mjs +1 -1
  17. package/src/connection-client-sync.mjs +1 -0
  18. package/src/connection-management.mjs +5 -0
  19. package/src/connection-policy.mjs +2 -2
  20. package/src/connection-routing.mjs +3 -1
  21. package/src/connection-runtime.mjs +37 -2
  22. package/src/connection-view.mjs +11 -2
  23. package/src/context-compaction-plan.mjs +122 -0
  24. package/src/context-compaction-seal.mjs +56 -0
  25. package/src/context-compaction-wire.mjs +137 -0
  26. package/src/context-compaction.mjs +161 -0
  27. package/src/context-metrics.mjs +1 -1
  28. package/src/conversation-source-guard.mjs +15 -5
  29. package/src/dashboard/connections.js +33 -3
  30. package/src/dashboard/index.html +9 -1
  31. package/src/dashboard/language.js +28 -0
  32. package/src/dashboard/preferences.js +1 -1
  33. package/src/dashboard/ui.js +3 -0
  34. package/src/dashboard-api.mjs +2 -2
  35. package/src/doctor-compat.mjs +1 -1
  36. package/src/http-transport.mjs +1 -1
  37. package/src/local-privacy.mjs +15 -7
  38. package/src/lock.mjs +9 -2
  39. package/src/model-capabilities.mjs +17 -4
  40. package/src/privacy-detection.mjs +4 -3
  41. package/src/privacy-transform.mjs +20 -6
  42. package/src/provider-cooldown.mjs +43 -0
  43. package/src/provider-runtime.mjs +8 -5
  44. package/src/providers/api-model-metadata.mjs +7 -0
  45. package/src/providers/api.mjs +44 -12
  46. package/src/request-context.mjs +5 -0
  47. package/src/response-failures.mjs +4 -2
  48. package/src/responses-bridge.mjs +12 -5
  49. package/src/responses-handler.mjs +79 -1
  50. package/src/responses-proxy.mjs +18 -5
  51. package/src/responses-request.mjs +11 -4
  52. package/src/safe-upstream-error.mjs +59 -9
  53. package/src/service-control.mjs +8 -1
  54. package/src/settings-preferences.mjs +3 -3
  55. package/src/source-import.mjs +51 -0
  56. package/src/stream-performance.mjs +8 -5
  57. package/src/upstream-body.mjs +1 -1
  58. package/src/upstream-error-capture.mjs +29 -0
  59. package/src/usage-analysis.mjs +2 -2
  60. package/src/usage-query.mjs +5 -2
  61. package/src/usage-store.mjs +2 -1
  62. package/src/user-settings.mjs +1 -1
package/README.md CHANGED
@@ -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,20 +48,23 @@ 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` |
57
+ | Inspect compression | `ccdx compact status` / `ccdx compact enable` / `ccdx compact disable` |
54
58
  | Inspect failures | `ccdx requests --failed` |
55
- | Read usage | `ccdx usage` / `ccdx usage --provider google --days 7` / `ccdx usage --scope run` |
59
+ | Capture one upstream error | `ccdx requests diagnose --source api_work --model model-id --yes` |
60
+ | Read usage | `ccdx usage` / `ccdx usage --provider google --days 7` / `ccdx usage --purpose diagnostic` / `ccdx usage --scope run` |
56
61
  | Inspect preferences | `ccdx config show --effective` |
57
62
  | Inspect local masking | `ccdx config privacy status` |
58
63
  | Check local setup | `ccdx doctor` |
59
64
 
60
65
  Use `ccdx help` or `ccdx <command> --help` for options. The CLI uses English; the Web UI supports English and Chinese.
61
66
 
62
- **1.3 uses one command tree.** Old command names and the `codex-copilot-dx` executable have been removed. This changes command entrypoints, not saved accounts, model selections or chats. See the [command reference](docs/REFERENCE.md#commands).
67
+ **CCDX uses one command tree.** Old command names and the `codex-copilot-dx` executable have been removed. This changes command entrypoints, not saved accounts, model selections or chats. See the [command reference](docs/REFERENCE.md#commands).
63
68
 
64
69
  ## Features and maintenance
65
70
 
package/bin/cli.mjs CHANGED
@@ -331,7 +331,10 @@ const clientVersions = {
331
331
  if (shuttingDown || serviceWorker?.warming || serviceWorker?.draining || serviceWorker?.preserving) return Promise.resolve(clientVersions.snapshot());
332
332
  versionModule ||= import("../src/client-versions.mjs").then(({ createClientVersionMonitor, clientVersionName }) => {
333
333
  if (shuttingDown) return null;
334
- versionMonitor = createClientVersionMonitor({ onChange: names => console.log(status("info", `Installed ${names.map(clientVersionName).join(" and ")} updated; check integration in the WebUI or ccdx doctor`)) });
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());
@@ -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
- Claude App 3.x and 4.x share the inspected effort-capable adapter. Later unknown major versions retain conservative routes and preserve existing shared capability settings. Contiguous effort declarations select the source-qualified reasoning route; a gapped declaration with at least two lower contiguous levels can expose that safe prefix with an App maximum cap, while retaining the complete upstream declaration and reporting the hidden levels as limited. Prior route spellings remain accepted for existing conversations. Resynchronization carries long-context preference and model order between the two known source-qualified spellings, and replaces only owned shared capability fields. No undeclared effort is added. The sidebar brand places its shared atom icon and text in one grid row so the intro icon's two-row span cannot offset the label.
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
 
@@ -1191,12 +1191,41 @@ The image and input-suggestion panels share `codex-launch-control.mjs`. `codex-a
1191
1191
 
1192
1192
  The managed Codex catalog projects explicit source input modalities ahead of native templates and checks GitHub priority eligibility against the full live source registry. Unknown modality metadata keeps the prior fallback. Source identities, selected models and routing remain unchanged.
1193
1193
 
1194
- `safe-upstream-error.mjs` reads only failed image or custom API responses, with a 64 KiB size bound, a 200 ms timer and four concurrent readers. Only fixed code/status pairs and local messages escape the reader. Original status, stable CCDX codes and validated Retry-After remain intact. Error-header callbacks normally release request admission before the optional body read; an eligible explicit compatibility rejection retains admission through its one retry. Image processing slots are released before their error read. Count-token singleflight forwards callbacks only to the appropriate waiters. Successful requests never invoke the reader.
1194
+ `safe-upstream-error.mjs` reads only failed image or custom API responses, with a 64 KiB size bound, a 200 ms timer and four concurrent readers. Default evidence exposes only fixed categories, validated parameter paths, numeric maxima and local messages. Original status, stable CCDX codes and validated Retry-After remain intact. Error-header callbacks normally release request admission before the optional body read; an eligible explicit compatibility rejection retains admission through its one retry. Image processing slots are released before their error read. Count-token singleflight forwards callbacks only to the appropriate waiters. Successful requests never invoke the reader.
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. A detected unrecognized system Claude App major prevents later writes to shared capability fields without changing existing routing or model aliases. The existing model-refresh timer, manual checks and a nonblocking service-reuse notification schedule observation; a disabled timer leaves startup and manual checks available.
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
+ `upstream-error-capture.mjs` owns explicit, process-local one-shot consent shared by API instances. The existing same-origin settings action and `requests diagnose` command arm an enabled Messages source/model for ten minutes. The first matching 400/422 claims the capture before reading its body, using the existing reader bounds. Explicit diagnostic text removes the actual source key and common credential/content echoes before the 512-character bound. State retains the result even if an existing compatibility retry succeeds; cancellation invalidates in-flight completion. Capturing does not write settings, request bodies or transcripts, add timers or make model calls. Success paths do not scan diagnostic text.
1210
+
1211
+ `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.
1212
+
1213
+ 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.
1214
+
1215
+ 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.
1216
+
1217
+ `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.
1218
+
1219
+
1220
+ ## Shared context compression
1221
+
1222
+ `context-compaction.mjs` owns native-first execution, source/model-scoped support observations, two-operation admission, bounded recovery and internal usage attribution. `context-compaction-plan.mjs` preserves user/system content, opaque blocks and connected tool-call/result components while selecting completed assistant/tool history. Chunk work is sized by UTF-8 bytes under explicit or reported source limits; it is not an exact tokenizer. Four chunks and one merge are followed by at most one original-operation retry. Unknown limits and incomplete outputs fail closed, without editing client transcripts.
1223
+
1224
+ `context-compaction-wire.mjs` builds source-local summary requests with unchanged model/reasoning controls and no executable tools. Its bounded JSON/SSE reader accepts only complete text summaries, tracks cumulative usage without inventing missing fields, and cancels without waiting for a stalled source cancellation. Fragment arrays avoid repeated growing-text copies. Existing native stream forwarding stays unchanged.
1225
+
1226
+ `context-compaction-seal.mjs` distinguishes gateway summaries from native-source envelopes. AES-GCM uses the existing local client identity and connection scope; no new key file is introduced. Native opaque state remains byte-for-byte inside its envelope, cryptographically bound to its private restoration map. Only authorized input expansion imports the map into the response privacy session. `privacy-transform` exposes process-local mapping snapshots only for this purpose; normal response completion releases maps. No prompt or plaintext mapping is persisted.
1227
+
1228
+ Responses accepts both the compact endpoint and a terminal inline compaction trigger. It expands owned state during its existing history traversal, before provider ownership checks; vendor state is never reinterpreted. The complete compacted output remains canonical. Claude compaction is classified only by native gateway hint metadata, and Antigravity by explicit request types plus observed source ownership. Unattributed background traffic keeps its existing policy. Settings, CLI/TUI and context/usage observations expose the same service; non-compaction inference adds no counting or summary calls.
1229
+
1230
+
1231
+ The implementation takes the native/gateway-state ownership separation from [Magpie's native compaction design](https://github.com/yetone/magpie/blob/main/internal/gateway/native_compaction.go). The empty-reasoning boundary follows [Floway's input fix](https://github.com/Menci/Floway/commit/02f819f41a2e), and source/model-scoped observations follow its isolation principle. Counting/generation control parity follows [LiteLLM's correction](https://github.com/BerriAI/litellm/commit/5849906ddb2f); source endpoint declarations retain the protocol-selection principle demonstrated by [CC Switch](https://github.com/farion1231/cc-switch/commit/86c749b98e76). No upstream runtime, Redis or wholesale intermediate representation is added.
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 |
@@ -108,7 +109,7 @@ requests and check ordinary Gemini chat when accepting a new App version.
108
109
 
109
110
  Messages observes the selected model's effective capability snapshot after alias resolution. Legacy connections use cached catalog metadata when no snapshot is supplied. Missing or invalid windows remain unknown; no size is inferred from model names. Existing provider-applied capability observations keep their priority. This adds neither catalog refresh nor inference calls, and does not change request bodies, replies or token-count probes.
110
111
 
111
- Only explicit, bounded session IDs can link requests. Local display identifiers replace native IDs and titles; account/profile, app, source, model and declared subagent identities remain separate. Unidentified requests appear individually. Concurrent observations are points rather than a connected conversation curve. Compaction records cover observed Responses compact calls, not every client-side summary, and their elapsed time includes the whole gateway request. No before/after size is invented from summary output tokens.
112
+ Only explicit, bounded session IDs can link requests. Local display identifiers replace native IDs and titles; account/profile, app, source, model and declared subagent identities remain separate. Unidentified requests appear individually. Concurrent observations are points rather than a connected conversation curve. Compaction records cover observed Responses compact calls and explicitly classified Claude/Antigravity compression tasks, and their elapsed time includes the whole gateway request. No before/after size is invented from summary output tokens.
112
113
 
113
114
  Each protocol observer retains at most 64 series of 64 request points and 16 compaction records, plus 20 unidentified requests. These numeric observations are memory-only and reset on restart. The page reads them on demand and after observed request completion through the existing dashboard refresh controller; ordinary status payloads do not include them. There is no prompt storage, text tokenization, transcript scan, extra provider request, content breakdown or compression control.
114
115
 
@@ -138,6 +139,46 @@ 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
+ For an explicit one-shot investigation, run `ccdx requests diagnose --source ID --model ID --yes` on the running service. It captures the first matching Messages HTTP 400/422 within ten minutes, including a failure recovered by an existing compatibility retry. It retains at most 512 characters of redacted technical explanation in process memory; an explanation can still contain an unlabelled request fragment. No request body is saved and no model call is made. Read the result with `ccdx requests diagnose --format json`; clear or cancel it with `ccdx requests diagnose --cancel --yes`. Restarting clears the capture. A missing, oversized or slow error body produces `unavailable`; successful requests and other sources/models do not consume it. This diagnoses the rejection and does not change request parameters or prove the original problem is fixed.
161
+
162
+ 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.
163
+
164
+ New requests accept the explicit local `X-CCDX-Purpose` value `conversation`, `compaction`, `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.
165
+
166
+ ## Unified context compression
167
+
168
+ `ccdx compact status` reads the running service's native and gateway observations without sending a model request. `ccdx compact enable|disable --yes` controls automatic gateway fallback; existing source-native compression stays available. The same preference is in **Settings → Context compression** and `ccdx config set context_compaction_enabled true|false --yes`.
169
+
170
+ Applications retain their native compression triggers. Codex uses `/v1/responses/compact` or its terminal `compaction_trigger` on Responses; Claude uses its explicit `x-claude-code-request-class: compaction` hint; Antigravity uses `summarization` and `checkpoint` request types. Claude synchronization enables its supported native gateway hint headers through owned settings. Existing running clients may need a normal reopen to adopt that environment setting; CCDX never force-restarts an App and never detects compaction by reading prompt wording.
171
+
172
+ Native compression is tried first. A missing Responses compact operation or a confirmed source input-length rejection can enter bounded recovery using the same authorized source, model and reasoning controls. Authentication, quota and unrelated parameter failures do not trigger recovery. Actual unsupported-endpoint observations are scoped to the source connection and model and expire after one minute. Unknown input windows remain unknown; a source-reported limit bounds a stale larger declaration. No paid discovery probes run.
173
+
174
+ Recovery preserves human messages, system instructions, tool declarations, signed/opaque state, and unfinished tool pairs. Only completed eligible historical assistant/tool records are summarized. Up to four UTF-8-sized segments and one merge job are allowed, followed by at most one retry of the original Messages/Chat/Gemini compression request. Segment sizing is a byte-based work bound, not a claimed exact token count. Recovery has a five-minute deadline and at most two concurrent gateway recoveries. An unknown window, protected-only history, oversized workload, incomplete summary or repeated rejection fails explicitly while keeping the original conversation. There is no recursive recovery or automatic source/account/model switch. Gateway recovery handles pre-output HTTP rejections; an already-started source stream is never replayed.
175
+
176
+ Codex gateway summaries use authenticated local compression states. Only CCDX expands its own states after local authorization; vendor states stay opaque and retain their connection ownership. Source-native states carrying private placeholders preserve the required restoration map in an authenticated gateway envelope. Maps are never sent upstream or stored as plaintext files. Gateway-owned states require CCDX 1.4 or later; keep the complete local transcript before any downgrade, since older gateways cannot directly expand this versioned state. Imported maps retain the existing mapping limits and are released with their request. A changed client identity or connection cannot silently reuse the state.
177
+
178
+ Antigravity compression follows a previously observed conversation source/model. Hashed source ownership also survives a service restart. When attribution is unavailable, the already-authorized background policy is retained; the gateway does not infer a Google route from a default background model name. Other title, search and image behavior is unchanged. The native Google route retains its existing privacy policy; Copilot compression stays inside the existing masking session.
179
+
180
+ Internal summary jobs record returned usage separately with purpose `compaction`, including reported partial usage before failure. The Codex aggregate response is not logged a second time. Missing counts remain unknown and genuine zero cache counts stay zero. `ccdx usage --purpose compaction` and the WebUI purpose filter show this work; every purpose remains in default totals. Observed native Claude/Antigravity compression tasks also appear in context observations when explicit session metadata is available. Summary output length is not presented as a verified post-compression context size.
181
+
141
182
  ## Microsoft 365
142
183
 
143
184
  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 +195,7 @@ Catalog diagnostics distinguish local cached data from an online response and ex
154
195
  - **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
196
  - **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
197
  - **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 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. A detected unrecognized Claude App major version preserves existing shared capability fields during later synchronization. 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.
198
+ - **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
199
  - **Cache cleanup:** adding `--history` can break the next continuation. It does not delete client transcripts or generated images.
159
200
 
160
201
  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 +206,13 @@ Native records use source `google`; Copilot records use `github`. Google output
165
206
 
166
207
  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
208
 
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.
209
+ 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
210
 
170
211
  CLI and TUI subcommands share the same source/model/calendar semantics:
171
212
 
172
213
  ```sh
173
214
  ccdx usage --provider google --days 7
215
+ ccdx usage --purpose diagnostic
174
216
  ccdx usage --model 'github / gemini-4-carbon' --from 2026-11-01 --to 2026-11-13 --time-zone Asia/Shanghai
175
217
  ccdx usage --scope run --provider google
176
218
  ccdx requests --app antigravity --active
@@ -784,6 +826,8 @@ CLI/TUI, WebUI totals and daily analytics use the same paired evidence for cache
784
826
 
785
827
  Usage writes are asynchronous and batched under the existing cross-process rotation lock. Pending and in-flight records share a 4096-record / 4 MiB ceiling. If either ceiling is reached, new excess records are dropped with a warning and a status counter; inference does not wait or retry. Normal records and per-record rotation boundaries are unchanged. The bounded shutdown flush remains 1.5 seconds; disk failures and shutdown deadlines can prevent persistence, so usage is diagnostic rather than a billing ledger.
786
828
 
829
+ On Windows, asynchronous lock acquisition retries a transient `EPERM` within the existing lock deadline. It does not replay a protected write or remove another live owner's lock; persistent denial retains its original error.
830
+
787
831
  Repeated plain usage summaries reuse one bounded entry when retained files are unchanged, with the existing two-second recent-write guard and 256 KiB/128-group limit. Dashboard analytics keeps up to two independent aggregate checkpoints within 2 MiB. Its first read scans both retained logs. Later reads apply only append batches witnessed by this process under the existing write lock, with a 256 KiB pending-delta limit per checkpoint. Another process's writes, rotation, truncation, replacement, incomplete tails, warnings, future/undated records and oversized results fall back to a complete read. Queries remain scoped by source, time zone and local date; returned results are cloned and identical concurrent reads share work. The asynchronous writer supplies file-version evidence only while analytics checkpoints exist. There is no persistent index, background poll or added model request.
788
832
 
789
833
  Diagnostic redaction removes Basic authorization payloads and URL userinfo, and consumes escaped quotes inside sensitive JSON fields. Ordinary Basic-related prose, safe host/path information and error codes are retained. These protections apply to existing failure/status/debug diagnostics, not forwarded requests or upstream response bodies. They do not make arbitrary upstream prose guaranteed safe to share.
@@ -909,6 +953,8 @@ Privacy failures have a separate local diagnostic origin. Response-restoration f
909
953
 
910
954
  The optional component is pinned to v1.3.13. Verified older components, including 1.3.10, retain their original whole-text behavior. ABI 1 is unchanged; window reuse, advisory window plans and acknowledged cancellation are advertised capabilities. Plans contain only text indices and window counts, never request text. Startup retains its previous inexpensive preflight; accelerator initialization remains lazy. Native CI checks both cold detection and startup-plus-cold cost. Verified 1.3.6 and 1.3.9 installations remain compatible. New component receipts bind their protocol ABI and model revision before older versioned components can be reused. On Intel Macs where CoreML selects CPU, windows below 128 tokens use the existing native int8 reader; longer windows, GPU, Neural Engine and ARM selection retain their prior policy. Its source and license notices are in `native/privacy-guard` and `src/privacy-notices.txt`. AstrLink Guard model files use their publisher's Apache-2.0 license.
911
955
 
912
- Paired timing comparisons report cold, startup-plus-first-check, append and hot-check observations without blocking publication. Classifier correctness, byte verification and reuse assertions remain blocking. Real-use request records expose local-check duration and errors for observation after upgrading; fixed-machine results do not establish sustained real-use performance.
956
+ Hosted CI timing comparisons report cold, startup-plus-first-check, append and hot-check observations without blocking publication. Fixed-machine paired comparisons block publication: cold/startup permits +10%; append requires its 95% paired interval upper bounds to meet both +5% and +0.5 ms; hot reuse keeps the existing zero-slowdown and A/A repeatability rule. Both append limits must pass independently; neither is waived by A/A noise. Classifier correctness, byte verification and reuse assertions remain blocking. Real-use request records expose local-check duration and errors for observation after upgrading; fixed-machine results do not establish sustained real-use performance.
913
957
 
914
958
  Usage tables and analytics model selectors display the current saved name for a configured custom API source. Filtering and aggregation retain the stable provider/model keys. Renaming a source updates its label without merging records; a deleted or unknown source keeps its ID. Existing historical records are not rewritten.
959
+
960
+ For a JavaScript-only privacy change with unchanged native component bytes, `scripts/privacy-candidate-replay.mjs --baseline-commit FULL_SHA --reuse-component-path true` compares the complete baseline source and reuses the same verified executable path, matching the installed component lifecycle. The original workloads and paired policy stay unchanged. Both variants use production waits. Run a qualified A/A control before A/B; unqualified controls do not establish a regression or a pass.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.3.27",
3
+ "version": "1.4.0",
4
4
  "description": "Local gateway for Codex, Claude and Gemini Antigravity with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/adapter.mjs CHANGED
@@ -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";
@@ -37,6 +37,8 @@ import { httpError } from "./http-errors.mjs";
37
37
  import { createRequestAdmission } from "./request-admission.mjs";
38
38
  import { PROVIDER_MANAGEMENT_PATH, handleProviderManagement } from "./provider-management.mjs";
39
39
  import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
40
+ import { createContextCompactionService } from "./context-compaction.mjs";
41
+ import { readClientGatewayKeys } from "./client-gateway-keys.mjs";
40
42
 
41
43
  export {
42
44
  abortErrorStatusCode,
@@ -180,12 +182,16 @@ export function createAdapterHandler(options = {}) {
180
182
  const imagePressure = options.imagePressure || createResponsesImagePressureController();
181
183
  const responseFailures = options.responseFailures || createResponseFailureDiagnostics();
182
184
  const privacy = options.privacy || options.providerRuntime?.privacy || createLocalPrivacy({ env: options.env, home: options.dashboardOptions?.home });
185
+ const compaction = options.compaction || options.providerRuntime?.compaction || createContextCompactionService({ enabled() {
186
+ try { return readUserSettings({ env: options.env, home: options.dashboardOptions?.home, strict: true }).context_compaction_enabled !== false; } catch { return false; }
187
+ } });
188
+ const compactionOptions = { compaction, compactionKey: options.compactionKey || (() => readClientGatewayKeys({ env: options.env, home: options.dashboardOptions?.home, create: false }).codex) };
183
189
  let carbonSearch = null, copilotWeb = null;
184
190
  let antigravity = null, antigravityLoading = null;
185
191
  const geminiRuntime = async () => {
186
192
  if (!antigravityLoading) antigravityLoading = (async () => {
187
193
  const { createAntigravityRuntime } = await import("./antigravity-runtime.mjs");
188
- antigravity = createAntigravityRuntime({ client: codexClient, models: () => codexModelRegistry?.models || [], privacy, acquireRequest,
194
+ antigravity = createAntigravityRuntime({ client: codexClient, models: () => codexModelRegistry?.models || [], privacy, compaction, acquireRequest,
189
195
  env: options.env, home: options.dashboardOptions?.home, requestBodyTimeoutMs, upstreamTimeoutMs, streamIdleTimeoutMs,
190
196
  ...options.antigravityOptions });
191
197
  return antigravity;
@@ -253,6 +259,7 @@ export function createAdapterHandler(options = {}) {
253
259
  },
254
260
  });
255
261
  const responsesHandler = createResponsesHandler({
262
+ ...compactionOptions,
256
263
  privacy,
257
264
  validateConversation: (body, headers, source, signal) => options.providerRuntime?.validateConversation?.(body, headers, source, signal),
258
265
  resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
@@ -276,6 +283,8 @@ export function createAdapterHandler(options = {}) {
276
283
  upstreamTimeoutMs,
277
284
  });
278
285
  const responsesCompactHandler = createResponsesCompactHandler({
286
+ ...compactionOptions,
287
+ responsesFn, chatCompletionsFn, getCachedModelEndpointsFn,
279
288
  privacy,
280
289
  validateConversation: (body, headers, source, signal) => options.providerRuntime?.validateConversation?.(body, headers, source, signal),
281
290
  resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
@@ -305,12 +314,13 @@ export function createAdapterHandler(options = {}) {
305
314
  modelRegistry: provider.registry, now: options.now, openAIModelEnv: { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" },
306
315
  autoReviewModelResolver: () => { const preference = options.providerRuntime.providerPreference?.(provider.id) || options.providerRuntime.selection().m365;
307
316
  return { model: preference?.auto_review_model, reasoningEffort: preference?.auto_review_effort === undefined ? Object.hasOwn(provider, "defaultReviewEffort") ? provider.defaultReviewEffort : "low" : preference.auto_review_effort }; },
308
- requestBodyTimeoutMs, responsesPayloadOptions: options.responsesPayloadOptions, responseFailures,
317
+ ...compactionOptions, requestBodyTimeoutMs, responsesPayloadOptions: options.responsesPayloadOptions, responseFailures,
309
318
  streamHandshakeTimeoutMs, streamIdleTimeoutMs, upstreamTimeoutMs };
310
319
  providerHandlers.set(provider, {
311
320
  responses: createResponsesHandler({ ...common, responsesFn: provider.client.responses, chatCompletionsFn: provider.client.chatCompletions,
312
321
  getCachedModelEndpointsFn: provider.client.getCachedModelEndpoints }),
313
- compact: createResponsesCompactHandler({ ...common, responsesCompactFn: provider.client.responsesCompact }),
322
+ compact: createResponsesCompactHandler({ ...common, responsesCompactFn: provider.client.responsesCompact, responsesFn: provider.client.responses, chatCompletionsFn: provider.client.chatCompletions,
323
+ getCachedModelEndpointsFn: provider.client.getCachedModelEndpoints }),
314
324
  });
315
325
  }
316
326
  return providerHandlers.get(provider);
@@ -480,7 +490,8 @@ export function createAdapterHandler(options = {}) {
480
490
  && !DASHBOARD_API_PATHS.has(pathname)
481
491
  && !((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname));
482
492
  const complete = trackRequest ? requestMetrics.begin(routeName) : () => {};
483
- const streamPerformance = trackRequest && !isDiscoveryRequest(req.method, pathname) ? streamPerformanceMetrics.begin(routeName, { requestId, application: requestApplication(req.headers, routeName === "antigravity" ? "gemini_app" : "api") }) : null;
493
+ const purpose = requestPurpose(req.headers["x-ccdx-purpose"]);
494
+ const streamPerformance = trackRequest && !isDiscoveryRequest(req.method, pathname) ? streamPerformanceMetrics.begin(routeName, { requestId, purpose, application: requestApplication(req.headers, routeName === "antigravity" ? "gemini_app" : "api") }) : null;
484
495
  let finishTerminalActivity = () => {};
485
496
  if (trackRequest && !isDiscoveryRequest(req.method, pathname) && ["responses", "responses_compact", "messages", "images", "image_mcp", "search", "antigravity"].includes(routeName)) {
486
497
  try {
@@ -538,6 +549,7 @@ export function createAdapterHandler(options = {}) {
538
549
  try {
539
550
  context = {
540
551
  requestId,
552
+ purpose,
541
553
  pathname,
542
554
  showRequestId: options.showRequestId === true,
543
555
  includeHttpErrorDetails: options.includeHttpErrorDetails === true || process.env.CCDX_HTTP_ERROR_DETAILS === "1",
@@ -1,4 +1,4 @@
1
- import {randomUUID} from "node:crypto";
1
+ import {randomUUID,createHash} from "node:crypto";
2
2
  import {buildResponsesUsageRecord,recordUsage} from "./usage-store.mjs";
3
3
  import {createRequestAbort,readJsonBody,readBoundedResponseText,writeOrDrain,httpError,sendJsonError} from "./http-transport.mjs";
4
4
  import {safeUpstreamResponseHeaders} from "./upstream-headers.mjs";
@@ -9,6 +9,10 @@ import {createPrivacyTextFragments} from "./privacy-stream.mjs";
9
9
  import {createGoogleResponseObserver,googleUsageEvent} from "./antigravity-usage.mjs";
10
10
  import {currentRequestContext,observeRequestedModel} from "./request-context.mjs";
11
11
  import {markUpstreamStarted,markUpstreamHeaders,markFirstOutput,markOutputTokens,markRequestObservation,markResponseModel,markResponseTerminal} from "./stream-performance.mjs";
12
+ import {isCompactionRequest} from "./context-compaction.mjs";
13
+ import {compactionSummarizer} from "./context-compaction-wire.mjs";
14
+ import {requestPurpose} from "./request-context.mjs";
15
+ import {observeContextSession} from "./context-metrics.mjs";
12
16
 
13
17
  const PREFIX="/antigravity";
14
18
  const MAX_REPLY=64*1024*1024;
@@ -33,9 +37,9 @@ function groundedSearch(result,query){
33
37
  }
34
38
 
35
39
  export function createAntigravityHandler({client,models=()=>[],selectedModels=()=>null,enabled=()=>false,privacy,searchFn,imageFn,guardSource,acquireRequest=async()=>()=>{},
36
- recordUsageFn=recordUsage,fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,streamIdleTimeoutMs=60000}={}) {
40
+ compaction,compactionProfile=()=>"github",rememberConversationSource=()=>{},resolveCompactionSource=()=>null,recordUsageFn=recordUsage,fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,streamIdleTimeoutMs=60000}={}) {
37
41
  if(![GOOGLE_ORIGIN,"https://cloudcode-pa.googleapis.com"].includes(googleOrigin))throw new Error("Unrecognized Google control origin");
38
- let active=0,observed=false,catalogModels=null;
42
+ let active=0,observed=false,catalogModels=null;const nativeWindows=new Map();
39
43
  const counts={total:0,google:0,copilot:0,search:0,images:0,failed:0};
40
44
  const handler=async(req,res)=>{
41
45
  const abort=createRequestAbort(req,res);let release=()=>{},session,usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
@@ -64,9 +68,14 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
64
68
  const method=match[1];
65
69
  abort.setTimeout(requestBodyTimeoutMs,"request_body_timeout");release=await acquireRequest(req,{signal:abort.signal});
66
70
  if(req.method==="POST"&&!/^application\/json(?:;|$)/i.test(req.headers["content-type"]||""))throw httpError("Antigravity requires JSON",415);
67
- const body=req.method==="POST"?await readJsonBody(req,{admission:release,signal:abort.signal,parse:parseBody}):null;
71
+ let body=req.method==="POST"?await readJsonBody(req,{admission:release,signal:abort.signal,parse:parseBody}):null;
68
72
  const context=currentRequestContext();if(context)context.application="gemini_app";
73
+ const compacting=isCompactionRequest("gemini",body);
74
+ if(compacting&&context){context.purpose=requestPurpose(req.headers["x-ccdx-purpose"],"compaction");context.streamPerformance?.setPurpose(context.purpose)}
75
+ if(compacting)markRequestObservation({compaction:1});
69
76
  if(body?.model)observeRequestedModel(body);
77
+ const compactBinding=compacting?await resolveCompactionSource(body):null;
78
+ if(compactBinding?.model)body={...body,model:compactBinding.model};
70
79
  markRequestObservation({requested_model:context?.requestedModel});
71
80
  abort.setTimeout(upstreamTimeoutMs,"upstream_timeout");
72
81
  const generation=["streamGenerateContent","generateContent"].includes(method);
@@ -75,13 +84,22 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
75
84
  if(generation){
76
85
  usageModel=body.model;usageProvider="google";usageMode=method==="streamGenerateContent"?"sse":"json";
77
86
  if(context){context.provider="google";context.streamPerformance?.setProvider?.("google")}
78
- markRequestObservation({usage_state:"pending"});markUpstreamStarted(method==="streamGenerateContent");
87
+ observeContextSession(null,{session_id:body.request?.labels?.root_cascade_id||body.request?.labels?.cascade_id},{profileId:()=>"google:gemini-native"},"gemini");
88
+ markRequestObservation({usage_state:"pending"});
79
89
  }
80
- const upstream=await fetchGoogle(googleOrigin+route+local.search,{method:req.method,headers:{...nativeHeaders(req),...(body?{"content-type":"application/json"}:{})},
81
- ...(body?{body:JSON.stringify(body)}:{}),signal:abort.signal,redirect:"error"});
82
- if(generation)markUpstreamHeaders(upstream.status);
90
+ const open=async(value,options={})=>{
91
+ const internal=options.internal===true,path=internal?"/v1internal:streamGenerateContent?alt=sse":route+local.search;
92
+ if(generation){abort.setTimeout(upstreamTimeoutMs,"upstream_timeout");markUpstreamStarted(internal||method==="streamGenerateContent")}
93
+ const result=await fetchGoogle(googleOrigin+path,{method:internal?"POST":req.method,headers:{...nativeHeaders(req),...(value?{"content-type":"application/json"}:{}),...(internal?{accept:"text/event-stream"}:{})},
94
+ ...(value?{body:JSON.stringify(value)}:{}),signal:options.signal||abort.signal,redirect:"error"});
95
+ if(generation)markUpstreamHeaders(result.status);return result;
96
+ };
97
+ const upstream=compacting&&compaction?await compaction.run({body,protocol:"gemini",scope:JSON.stringify(["gemini","google",createHash("sha256").update(req.headers.authorization||"").update(String(body.project||"")).digest("hex")]),
98
+ source:"google",client:"gemini",model:body.model,inputLimit:nativeWindows.get(body.model),outputAllowance:body.request?.generationConfig?.maxOutputTokens||0,native:open,options:{signal:abort.signal},
99
+ summarize:compactionSummarizer(body,"gemini",(value,options)=>open(value,{...options,internal:true})),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await open(body);
83
100
  if(method==="fetchAvailableModels"&&upstream.ok){
84
101
  const value=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:8*1024*1024,signal:abort.signal,label:"Google model catalog"}));
102
+ nativeWindows.clear();for(const[id,entry]of Object.entries(value.models||{}).slice(0,256))if(Number.isSafeInteger(entry?.maxTokens)&&entry.maxTokens>0){nativeWindows.set(id,entry.maxTokens);if(typeof entry.model==="string")nativeWindows.set(entry.model,entry.maxTokens)}
85
103
  const merged=mergeAntigravityModels(value,models(),selectedModels());
86
104
  catalogModels=Object.keys(merged.models).filter(id=>id.startsWith(ANTIGRAVITY_MODEL_PREFIX));
87
105
  res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"});res.end(JSON.stringify(merged));return;
@@ -115,15 +133,18 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
115
133
  }
116
134
  if(req.method!=="POST"||!body||typeof body.model!=="string"||!body.request)throw httpError("Invalid Antigravity generation request",400);
117
135
  const selection=selectedModels(),copilotModels=antigravityCopilotModels(models()),selected=copilotModels.find(model=>model.id===body.model&&(selection===null||selection.includes(model.id)));
118
- if(body.requestType==="agent"&&!selected){
136
+ if((body.requestType==="agent"||compactBinding?.source==="google")&&!selected){
119
137
  if(body.model.startsWith(ANTIGRAVITY_MODEL_PREFIX))throw httpError("The selected Copilot model is unavailable",503);
120
- await guardSource?.(body,"google",abort.signal);
138
+ if(body.requestType==="agent"||body.request?.labels?.root_cascade_id||body.request?.labels?.cascade_id)await guardSource?.(body,"google",abort.signal);
139
+ if(body.requestType==="agent")rememberConversationSource(body,"google");
121
140
  return await native();
122
141
  }
123
- if(body.requestType==="agent")await guardSource?.(body,"github",abort.signal);
142
+ if(body.requestType==="agent"||compactBinding?.source==="github")await guardSource?.(body,"github",abort.signal);
143
+ if(body.requestType==="agent")rememberConversationSource(body,"github");
124
144
  if(!copilotModels.length)throw httpError("Copilot access for Antigravity is paused or unavailable",503);
125
145
  observed=true;counts.copilot++;
126
146
  if(context){context.provider="github";context.streamPerformance?.setProvider?.("github")}
147
+ observeContextSession(null,{session_id:body.request?.labels?.root_cascade_id||body.request?.labels?.cascade_id},{profileId:()=>"github:codex"},"chat");
127
148
  const request=body.request;
128
149
  if(body.requestType==="web_search"){
129
150
  counts.search++;if(!searchFn)throw httpError("Copilot search is unavailable",503);
@@ -142,13 +163,16 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
142
163
  res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response}));return;
143
164
  }
144
165
  if(!["agent","checkpoint","summarization","title"].includes(body.requestType))throw httpError("Unsupported Antigravity inference type",400);
145
- const target=body.requestType==="agent"?selected:copilotModels.find(model=>model.model==="gemini-4-carbon"&&model.effort==="low");
166
+ const target=body.requestType==="agent"||compactBinding&&!compactBinding.background?selected:copilotModels.find(model=>model.model==="gemini-4-carbon"&&model.effort==="low");
146
167
  if(!target)throw httpError("Copilot Carbon is unavailable for Antigravity background tasks",503);
147
168
  const stream=method==="streamGenerateContent";usageModel=target.model;usageMode=stream?"sse":"json";usageProvider="github";
148
169
  const converted=antigravityToChat(request,{model:target.model,effort:target.effort,stream});
149
170
  markResponseModel(target.model);markRequestObservation({usage_state:"pending"});
150
171
  session=privacy?.prepareSession?await privacy.prepareSession(converted.chat,{protocol:"chat",client:"gemini",signal:abort.signal}):passthrough(converted.chat);
151
- const upstream=await client.chatCompletions(session.body,{signal:abort.signal,retryOptions:{retries:0}});
172
+ const callOptions={signal:abort.signal,retryOptions:{retries:0},onUpstreamStart:()=>abort.setTimeout(upstreamTimeoutMs,"upstream_timeout")};
173
+ const upstream=compacting&&compaction?await compaction.run({body:session.body,protocol:"chat",scope:JSON.stringify(["gemini","github",compactionProfile()]),source:"github",client:"gemini",
174
+ inputLimit:target.maxTokens,outputAllowance:session.body.max_completion_tokens||session.body.max_tokens||0,native:client.chatCompletions,options:callOptions,
175
+ summarize:compactionSummarizer(session.body,"chat",client.chatCompletions),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await client.chatCompletions(session.body,callOptions);
152
176
  markUpstreamHeaders(upstream.status);
153
177
  if(!upstream.ok){await upstream.body?.cancel();throw httpError("Copilot generation was refused (HTTP "+upstream.status+")",upstream.status)}
154
178
  if(!stream){
@@ -172,6 +196,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
172
196
  }
173
197
  res.end();
174
198
  }catch(error){
199
+ if(typeof error.code==="string"&&error.code.startsWith("ccdx_compaction_"))res.setHeader("x-should-retry","false");
175
200
  counts.failed++;
176
201
  outcome=abort.signal.aborted&&["client_closed","client_aborted"].includes(abort.reason)?"cancelled":"failed";markResponseTerminal(outcome);
177
202
  if(res.headersSent&&!res.writableEnded&&!res.destroyed){res.end("data: "+JSON.stringify({error:{code:error.statusCode||502,message:error.message}})+"\n\n");}
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs";
2
+ import {createHmac} from "node:crypto";
2
3
  import os from "node:os";
3
4
  import path from "node:path";
4
5
  import {execFile} from "node:child_process";
@@ -24,7 +25,13 @@ export function createAntigravityRuntime({client,models=()=>[],privacy,home=os.h
24
25
  exec=execute,searchFn,imageFn,guardSource,googleFetch,acquireRequest,readToken=()=>readSavedGithubToken(home),...timeouts}={}) {
25
26
  const options={home,env},guard=createConversationSourceGuard(options);
26
27
  const web=searchFn?null:createCopilotWeb({client,readToken});
27
- let app={status:"unknown"},route=null,lastOperation=null;
28
+ let app={status:"unknown"},route=null,lastOperation=null,compactionSalt;const conversationSources=new Map();
29
+ const conversationKey=body=>{
30
+ const id=body?.request?.labels?.root_cascade_id||body?.request?.labels?.cascade_id;
31
+ if(typeof id!=="string"||!id||id.length>160||/[\u0000-\u001f\u007f]/.test(id))return null;
32
+ compactionSalt||=readClientGatewayKeys({...options,create:false}).codex;
33
+ return createHmac("sha256",compactionSalt).update("antigravity-compression\0"+id).digest("hex");
34
+ };
28
35
  const settings=()=>{
29
36
  const saved=readUserSettings({...options,strict:true});
30
37
  if(saved[key]!==undefined&&typeof saved[key]!=="boolean")throw httpError("Invalid Gemini integration setting",409);
@@ -39,7 +46,19 @@ export function createAntigravityRuntime({client,models=()=>[],privacy,home=os.h
39
46
  return guard("gemini",profile,{messages:[]},{session_id:id},readClientGatewayKeys({...options,create:false}).codex,undefined,signal);
40
47
  });
41
48
  const handler=createAntigravityHandler({client,models:available,selectedModels:()=>settings().selected_models,enabled:()=>settings().configured,privacy,searchFn:searchFn||web.search,
42
- imageFn:imageFn||createAntigravityImages({client,models:available,privacy}),guardSource:sourceGuard,fetchGoogle:googleFetch,acquireRequest,...timeouts});
49
+ imageFn:imageFn||createAntigravityImages({client,models:available,privacy}),guardSource:sourceGuard,compactionProfile:()=>githubTokenFingerprint(readToken()||""),
50
+ rememberConversationSource(body,source){const key=conversationKey(body);if(!key||typeof body.model!=="string"||!/^[\w][\w./:@+-]{0,159}$/.test(body.model))return;conversationSources.delete(key);conversationSources.set(key,{source,model:body.model});while(conversationSources.size>256)conversationSources.delete(conversationSources.keys().next().value)},
51
+ async resolveCompactionSource(body){
52
+ const key=conversationKey(body);if(!key)return null;if(conversationSources.has(key))return conversationSources.get(key);
53
+ const id=body.request.labels.root_cascade_id||body.request.labels.cascade_id,owner=await guard.owner("gemini",id,compactionSalt);
54
+ const profileHash=value=>createHmac("sha256",compactionSalt).update(value).digest("hex");
55
+ if(owner===profileHash("google:gemini-native")){
56
+ if(body.model.startsWith("ccdx-copilot-"))throw httpError("The conversation belongs to another model source",409);
57
+ return{source:"google",model:body.model};
58
+ }
59
+ if(owner===profileHash("codex:"+githubTokenFingerprint(readToken()||"")))return{source:"github",background:true};
60
+ return null;
61
+ },fetchGoogle:googleFetch,acquireRequest,...timeouts});
43
62
  function snapshot(){
44
63
  const config=settings(),sourceEnabled=readAccessSettings(options).providers.github,activity=handler.snapshot();
45
64
  const listed=antigravityCopilotModels(models()).map(({id,model,displayName,effort,maxTokens})=>({id,model,name:displayName,effort,context_window:maxTokens,selected:config.selected_models===null||config.selected_models.includes(id)}));
@@ -52,6 +71,7 @@ export function createAntigravityRuntime({client,models=()=>[],privacy,home=os.h
52
71
  const reload=config.enabled&&sourceEnabled?(activity.catalog_models===null?null:JSON.stringify([...activity.catalog_models].sort())!==JSON.stringify(expected)):false;
53
72
  return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,models_reload_required:reload,app,route_observed:handler.snapshot().observed,
54
73
  model_source:"Google + GitHub Copilot",background_source:"GitHub Copilot",ordinary_chat_source:"Google (unchanged)",
74
+ compaction_source:"Observed conversation source; existing background policy when unassigned",
55
75
  models:listed,model_groups:[...groups.values()],activity,last_operation:lastOperation};
56
76
  }
57
77
  async function action(input={},baseUrl){