codex-copilot-dx 1.3.28 → 1.4.1

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 (50) hide show
  1. package/README.md +4 -1
  2. package/docs/ARCHITECTURE.md +23 -1
  3. package/docs/REFERENCE.md +34 -3
  4. package/package.json +1 -1
  5. package/src/adapter.mjs +13 -3
  6. package/src/antigravity-handler.mjs +44 -15
  7. package/src/antigravity-runtime.mjs +22 -2
  8. package/src/claude-capability-config.mjs +3 -2
  9. package/src/claude-client-config.mjs +2 -2
  10. package/src/claude-gateway.mjs +22 -4
  11. package/src/cli-command-spec.mjs +9 -4
  12. package/src/cli-management.mjs +28 -0
  13. package/src/cli-options.mjs +1 -1
  14. package/src/connection-routing.mjs +1 -0
  15. package/src/connection-runtime.mjs +11 -0
  16. package/src/context-compaction-plan.mjs +122 -0
  17. package/src/context-compaction-seal.mjs +56 -0
  18. package/src/context-compaction-wire.mjs +137 -0
  19. package/src/context-compaction.mjs +161 -0
  20. package/src/context-metrics.mjs +3 -2
  21. package/src/conversation-source-guard.mjs +15 -5
  22. package/src/dashboard/console.js +1 -1
  23. package/src/dashboard/index.html +14 -1
  24. package/src/dashboard/language.js +33 -0
  25. package/src/dashboard/preferences.js +1 -1
  26. package/src/dashboard/status.js +2 -2
  27. package/src/dashboard/tool-activity.js +153 -0
  28. package/src/dashboard/ui.css +26 -0
  29. package/src/dashboard/ui.js +2 -2
  30. package/src/dashboard.mjs +1 -0
  31. package/src/http-transport.mjs +1 -1
  32. package/src/local-privacy.mjs +15 -7
  33. package/src/lock.mjs +9 -2
  34. package/src/privacy-detection.mjs +4 -3
  35. package/src/privacy-transform.mjs +20 -6
  36. package/src/provider-runtime.mjs +8 -5
  37. package/src/providers/api.mjs +15 -4
  38. package/src/request-context.mjs +1 -1
  39. package/src/responses-bridge.mjs +14 -5
  40. package/src/responses-handler.mjs +81 -1
  41. package/src/responses-proxy.mjs +22 -5
  42. package/src/responses-request.mjs +11 -4
  43. package/src/safe-upstream-error.mjs +29 -11
  44. package/src/service-control.mjs +8 -1
  45. package/src/settings-preferences.mjs +3 -3
  46. package/src/stream-performance.mjs +19 -2
  47. package/src/tool-activity.mjs +135 -0
  48. package/src/upstream-body.mjs +1 -1
  49. package/src/upstream-error-capture.mjs +29 -0
  50. package/src/user-settings.mjs +1 -1
package/README.md CHANGED
@@ -54,7 +54,10 @@ Model availability depends on your account and service. Microsoft 365 also requi
54
54
  | Choose client models | `ccdx app codex models --edit` |
55
55
  | Preview client setup | `ccdx app claude-app sync --preview` |
56
56
  | Set up Antigravity | `ccdx app antigravity status` / `enable` / `open` |
57
+ | Inspect compression | `ccdx compact status` / `ccdx compact enable` / `ccdx compact disable` |
57
58
  | Inspect failures | `ccdx requests --failed` |
59
+ | Inspect observed tool calls | `ccdx requests tools` / `ccdx requests tools --active` |
60
+ | Capture one upstream error | `ccdx requests diagnose --source api_work --model model-id --yes` |
58
61
  | Read usage | `ccdx usage` / `ccdx usage --provider google --days 7` / `ccdx usage --purpose diagnostic` / `ccdx usage --scope run` |
59
62
  | Inspect preferences | `ccdx config show --effective` |
60
63
  | Inspect local masking | `ccdx config privacy status` |
@@ -62,7 +65,7 @@ Model availability depends on your account and service. Microsoft 365 also requi
62
65
 
63
66
  Use `ccdx help` or `ccdx <command> --help` for options. The CLI uses English; the Web UI supports English and Chinese.
64
67
 
65
- **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).
68
+ **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).
66
69
 
67
70
  ## Features and maintenance
68
71
 
@@ -1191,7 +1191,7 @@ 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
 
@@ -1206,6 +1206,8 @@ Responses and Messages parsers, Chat line reading and the privacy restoration la
1206
1206
 
1207
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
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
+
1209
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.
1210
1212
 
1211
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.
@@ -1213,3 +1215,23 @@ The API provider reuses a cached healthy network directly. Its Messages alias ta
1213
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.
1214
1216
 
1215
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.
1232
+
1233
+ ## Tool activity
1234
+
1235
+ `tool-activity.mjs` stores bounded, memory-only metadata behind each stream-performance observer. Existing parsed Responses items, Messages blocks and Gemini function calls supply tool names and scoped identifiers; no argument or output body is copied. The existing session/profile HMAC and application label isolate result matching. Results match call IDs, with a unique-name-only fallback for Gemini. Request completion changes generated calls to waiting, never to successful execution. Observable returned results, source failures and cancellation terminate the corresponding observations. Live response activity renews preparing observations with at most one notification per second per request. Missing evidence becomes unknown after 90 seconds, with a bounded late-result window. Snapshot reads perform lazy retention cleanup; there is no server polling loop.
1236
+
1237
+ The WebUI consumes this metadata through the existing activity subscription. `dashboard/tool-activity.js` draws only the selected style, caches layout/theme measurements, caps drawing at 30 fps and DPR 1.5, pauses hidden/off-screen/reduced-motion views, and stops terminal cues within 0.9 seconds. Local deadline timers stop stale activity even when the stream has no new events. Native controls, theme variables and the language dictionary preserve the existing UI contract. The read-only `requests tools` grammar also drives TUI discovery.
package/docs/REFERENCE.md CHANGED
@@ -39,6 +39,7 @@ For installation and first use, start with the [README](../README.md). This refe
39
39
  | `ccdx config reset --preview` / `restore` | Preview defaults or restore the pre-reset backup |
40
40
  | `ccdx requests [--failed] [--active]` | Inspect retained requests |
41
41
  | `ccdx requests show <request_id>` | Read one retained request |
42
+ | `ccdx requests tools [--active]` | Read observed tool-call metadata; no arguments or outputs |
42
43
  | `ccdx usage [--scope all\|run] [--provider ID] [--model ID] [--purpose VALUE] [--days N\|all]` | Read filtered retained usage or current-run totals |
43
44
  | `ccdx doctor [--online] [--compat] [--fix] [--json]` | Check local setup; optional access checks and repairs |
44
45
  | `ccdx doctor config` / `network` / `report` | Read configuration, routing or a redacted local report |
@@ -109,10 +110,18 @@ requests and check ordinary Gemini chat when accepting a new App version.
109
110
 
110
111
  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.
111
112
 
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, not every client-side summary, and their elapsed time includes the whole gateway request. No before/after size is invented from summary output tokens.
113
+ 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.
113
114
 
114
115
  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.
115
116
 
117
+ ## Observed tool calls
118
+
119
+ **Requests → Tool calls** uses the existing activity stream for Codex, Claude and Antigravity. Choose Grid, Beam ring, Orbit rings, Woven field or Off; this browser remembers the choice. Captions change with observed call preparation, waiting and returned results. Motion runs at a faster presentation cadence, independent of event frequency; it is not a progress percentage or a call counter. System reduced motion, hidden/off-screen views and Off stop continuous drawing. Returned results have at most a 0.9-second finish cue; failure, cancellation and unavailable evidence stop continuous motion.
120
+
121
+ Calls are correlated using their IDs and the existing app/profile/session scope. A model emitting a tool call does not prove that the client executed it. Only a matching returned result ends the wait; ambiguous name-only Gemini results stay unconfirmed. Without a reliable session, completed requests show unconfirmed tool state. After 90 seconds without observable tool or response activity, the UI pauses and shows that fresh status is needed. Late results can update retained unconfirmed observations for another five minutes. These display deadlines never cancel tools or change source timeouts.
122
+
123
+ The service retains at most 128 metadata observations per protocol observer, shows at most 32, and captures at most 32 calls per request. Finished observations remain for 15 seconds. It keeps safe tool names and local display IDs in memory, not arguments, outputs or raw conversation/call IDs. Input correlation checks a bounded recent suffix rather than scanning a transcript. It adds no provider calls, tokenization, activity connections or polling. `ccdx requests tools --format json` and the TUI Requests menu expose the same observations; `--active` selects preparing/waiting calls. Restarting clears these diagnostic observations.
124
+
116
125
  ## Sources and client access
117
126
 
118
127
  When Claude App encrypts a CCDX-owned gateway key, synchronization keeps the encrypted value and can still update owned model fields. The expected local key must match CCDX's ownership record; foreign profiles, addresses, rotated keys and user edits are not adopted. The sync result can report that the key was kept encrypted without claiming verified access. No system keystore decryption or extra permission is used.
@@ -157,9 +166,27 @@ Model details can declare `max_tool_definitions` and `supported_parameters`. Cat
157
166
 
158
167
  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
168
 
169
+ 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.
170
+
160
171
  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
172
 
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.
173
+ 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.
174
+
175
+ ## Unified context compression
176
+
177
+ `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`.
178
+
179
+ 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.
180
+
181
+ 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.
182
+
183
+ 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.
184
+
185
+ 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.
186
+
187
+ 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.
188
+
189
+ 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.
163
190
 
164
191
  ## Microsoft 365
165
192
 
@@ -808,6 +835,8 @@ CLI/TUI, WebUI totals and daily analytics use the same paired evidence for cache
808
835
 
809
836
  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.
810
837
 
838
+ 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.
839
+
811
840
  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.
812
841
 
813
842
  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.
@@ -933,6 +962,8 @@ Privacy failures have a separate local diagnostic origin. Response-restoration f
933
962
 
934
963
  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.
935
964
 
936
- 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.
965
+ 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.
937
966
 
938
967
  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.
968
+
969
+ 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.28",
3
+ "version": "1.4.1",
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
@@ -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);
@@ -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";
@@ -8,7 +8,11 @@ import {ANTIGRAVITY_MODEL_PREFIX,antigravityCopilotModels,mergeAntigravityModels
8
8
  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
- import {markUpstreamStarted,markUpstreamHeaders,markFirstOutput,markOutputTokens,markRequestObservation,markResponseModel,markResponseTerminal} from "./stream-performance.mjs";
11
+ import {markUpstreamStarted,markUpstreamHeaders,markFirstOutput,markOutputTokens,markRequestObservation,markResponseModel,markResponseTerminal,markToolActivity} 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,23 @@ 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
+ context?.streamPerformance?.observeToolInput?.(body.request,"gemini");
89
+ markRequestObservation({usage_state:"pending"});
79
90
  }
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);
91
+ const open=async(value,options={})=>{
92
+ const internal=options.internal===true,path=internal?"/v1internal:streamGenerateContent?alt=sse":route+local.search;
93
+ if(generation){abort.setTimeout(upstreamTimeoutMs,"upstream_timeout");markUpstreamStarted(internal||method==="streamGenerateContent")}
94
+ const result=await fetchGoogle(googleOrigin+path,{method:internal?"POST":req.method,headers:{...nativeHeaders(req),...(value?{"content-type":"application/json"}:{}),...(internal?{accept:"text/event-stream"}:{})},
95
+ ...(value?{body:JSON.stringify(value)}:{}),signal:options.signal||abort.signal,redirect:"error"});
96
+ if(generation)markUpstreamHeaders(result.status);return result;
97
+ };
98
+ 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")]),
99
+ source:"google",client:"gemini",model:body.model,inputLimit:nativeWindows.get(body.model),outputAllowance:body.request?.generationConfig?.maxOutputTokens||0,native:open,options:{signal:abort.signal},
100
+ summarize:compactionSummarizer(body,"gemini",(value,options)=>open(value,{...options,internal:true})),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await open(body);
83
101
  if(method==="fetchAvailableModels"&&upstream.ok){
84
102
  const value=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:8*1024*1024,signal:abort.signal,label:"Google model catalog"}));
103
+ 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
104
  const merged=mergeAntigravityModels(value,models(),selectedModels());
86
105
  catalogModels=Object.keys(merged.models).filter(id=>id.startsWith(ANTIGRAVITY_MODEL_PREFIX));
87
106
  res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"});res.end(JSON.stringify(merged));return;
@@ -89,6 +108,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
89
108
  const nativeStreaming=/text\/event-stream/i.test(upstream.headers.get("content-type")||"");
90
109
  if(generation)usageMode=nativeStreaming?"sse":"json";
91
110
  const observer=generation&&upstream.ok?createGoogleResponseObserver({streaming:nativeStreaming,onEvent:value=>{
111
+ markToolActivity(value,"gemini");
92
112
  const response=value?.response||value,event=googleUsageEvent(value);if(event)captureUsage(event);
93
113
  const candidates=response?.candidates||[];
94
114
  if(candidates.some(candidate=>candidate.content?.parts?.some(part=>part.functionCall||!part.thought&&typeof part.text==="string"&&part.text)))markFirstOutput("delta");
@@ -115,15 +135,19 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
115
135
  }
116
136
  if(req.method!=="POST"||!body||typeof body.model!=="string"||!body.request)throw httpError("Invalid Antigravity generation request",400);
117
137
  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){
138
+ if((body.requestType==="agent"||compactBinding?.source==="google")&&!selected){
119
139
  if(body.model.startsWith(ANTIGRAVITY_MODEL_PREFIX))throw httpError("The selected Copilot model is unavailable",503);
120
- await guardSource?.(body,"google",abort.signal);
140
+ if(body.requestType==="agent"||body.request?.labels?.root_cascade_id||body.request?.labels?.cascade_id)await guardSource?.(body,"google",abort.signal);
141
+ if(body.requestType==="agent")rememberConversationSource(body,"google");
121
142
  return await native();
122
143
  }
123
- if(body.requestType==="agent")await guardSource?.(body,"github",abort.signal);
144
+ if(body.requestType==="agent"||compactBinding?.source==="github")await guardSource?.(body,"github",abort.signal);
145
+ if(body.requestType==="agent")rememberConversationSource(body,"github");
124
146
  if(!copilotModels.length)throw httpError("Copilot access for Antigravity is paused or unavailable",503);
125
147
  observed=true;counts.copilot++;
126
148
  if(context){context.provider="github";context.streamPerformance?.setProvider?.("github")}
149
+ observeContextSession(null,{session_id:body.request?.labels?.root_cascade_id||body.request?.labels?.cascade_id},{profileId:()=>"github:codex"},"chat");
150
+ context?.streamPerformance?.observeToolInput?.(body.request,"gemini");
127
151
  const request=body.request;
128
152
  if(body.requestType==="web_search"){
129
153
  counts.search++;if(!searchFn)throw httpError("Copilot search is unavailable",503);
@@ -142,18 +166,21 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
142
166
  res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response}));return;
143
167
  }
144
168
  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");
169
+ const target=body.requestType==="agent"||compactBinding&&!compactBinding.background?selected:copilotModels.find(model=>model.model==="gemini-4-carbon"&&model.effort==="low");
146
170
  if(!target)throw httpError("Copilot Carbon is unavailable for Antigravity background tasks",503);
147
171
  const stream=method==="streamGenerateContent";usageModel=target.model;usageMode=stream?"sse":"json";usageProvider="github";
148
172
  const converted=antigravityToChat(request,{model:target.model,effort:target.effort,stream});
149
173
  markResponseModel(target.model);markRequestObservation({usage_state:"pending"});
150
174
  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}});
175
+ const callOptions={signal:abort.signal,retryOptions:{retries:0},onUpstreamStart:()=>abort.setTimeout(upstreamTimeoutMs,"upstream_timeout")};
176
+ const upstream=compacting&&compaction?await compaction.run({body:session.body,protocol:"chat",scope:JSON.stringify(["gemini","github",compactionProfile()]),source:"github",client:"gemini",
177
+ inputLimit:target.maxTokens,outputAllowance:session.body.max_completion_tokens||session.body.max_tokens||0,native:client.chatCompletions,options:callOptions,
178
+ summarize:compactionSummarizer(session.body,"chat",client.chatCompletions),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await client.chatCompletions(session.body,callOptions);
152
179
  markUpstreamHeaders(upstream.status);
153
180
  if(!upstream.ok){await upstream.body?.cancel();throw httpError("Copilot generation was refused (HTTP "+upstream.status+")",upstream.status)}
154
181
  if(!stream){
155
182
  const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));captureUsage(data);
156
- const result=chatToAntigravity(data,converted.originalNames);
183
+ const result=chatToAntigravity(data,converted.originalNames);markToolActivity(result,"gemini");
157
184
  outcome=result.candidates[0].finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome);
158
185
  res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response:session.restoreValue(result)}));return;
159
186
  }
@@ -161,6 +188,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
161
188
  res.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache"});
162
189
  const emit=chunk=>writeOrDrain(res,"data: "+JSON.stringify(chunk)+"\n\n",{signal:abort.signal});
163
190
  for await(const chunk of chatStreamToAntigravity(upstream,converted.originalNames,{onChunk:()=>abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout"),onUsage:captureUsage})){
191
+ markToolActivity(chunk,"gemini");
164
192
  const candidate=chunk.response?.candidates?.[0];
165
193
  for(const part of candidate?.content?.parts||[]){
166
194
  if(part.functionCall||typeof part.text==="string"&&part.text&&!part.thought)markFirstOutput("delta");
@@ -172,6 +200,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
172
200
  }
173
201
  res.end();
174
202
  }catch(error){
203
+ if(typeof error.code==="string"&&error.code.startsWith("ccdx_compaction_"))res.setHeader("x-should-retry","false");
175
204
  counts.failed++;
176
205
  outcome=abort.signal.aborted&&["client_closed","client_aborted"].includes(abort.reason)?"cancelled":"failed";markResponseTerminal(outcome);
177
206
  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){
@@ -65,7 +65,7 @@ export function claudeSharedCapabilityPlan({ app = [], code = [], support = {} }
65
65
  if (capabilities.length > 8000) limitations.push({ code: "capability_list_limited" });
66
66
  return { state: consumers.length ? "planned" : "not_configured", context_tokens: context || null,
67
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"] : [])],
68
+ preserve_fields: [...(!knownAdapters ? ["env.CLAUDE_CODE_MAX_CONTEXT_TOKENS", "env.CLAUDE_CODE_GATEWAY_HINT_HEADERS"] : []), ...(!knownAdapters || support.app_contract && !support.app_contract.fields.output ? ["env.CLAUDE_CODE_MAX_OUTPUT_TOKENS"] : [])],
69
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 : {},
70
70
  capabilities: capabilities.length <= 8000 ? capabilities : "", limitations };
71
71
  }
@@ -82,8 +82,9 @@ export function syncClaudeCapabilities(plan, options = {}) {
82
82
  const journal = readM365Json(m365Paths(options).ownership, { version: 1, operations: [] });
83
83
  const ownsCodeBase = journal.operations?.some(op => op.file === paths.code && op.keys?.join(".") === "env.ANTHROPIC_BASE_URL" && op.after === base);
84
84
  const conflict = Boolean(env.ANTHROPIC_BASE_URL || base && (!/^http:\/\/127\.0\.0\.1:\d+\/anthropic$/.test(base) || !ownsCodeBase));
85
- const ownedFields = ["env.CLAUDE_CODE_MAX_CONTEXT_TOKENS", "env.CLAUDE_CODE_MAX_OUTPUT_TOKENS", "env.CLAUDE_CODE_MODEL_CAPABILITIES"];
85
+ const ownedFields = ["env.CLAUDE_CODE_MAX_CONTEXT_TOKENS", "env.CLAUDE_CODE_MAX_OUTPUT_TOKENS", "env.CLAUDE_CODE_MODEL_CAPABILITIES", "env.CLAUDE_CODE_GATEWAY_HINT_HEADERS"];
86
86
  if (!conflict) {
87
+ if (plan.state === "planned" && !plan.limitations?.some(item => item.code === "client_version_unknown")) add(["env", "CLAUDE_CODE_GATEWAY_HINT_HEADERS"], "1");
87
88
  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]]) {
88
89
  let selected=value;
89
90
  if(key==="CLAUDE_CODE_MODEL_CAPABILITIES"&&selected){
@@ -158,7 +158,7 @@ export function reconcileClaudeConfiguration(operations, { restore = false, rest
158
158
  return withFileLockSync(`${journalPath}.lock`, () => {
159
159
  const journal = readM365Json(journalPath, { version: 1, operations: [] });
160
160
  const keys = new Map([
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"])],
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", "env.CLAUDE_CODE_GATEWAY_HINT_HEADERS"])],
162
162
  [paths.normal, new Set(["deploymentMode"])], [paths.threep, new Set(["deploymentMode"])],
163
163
  [paths.meta, new Set(["entries", "appliedId"])],
164
164
  [paths.profile, new Set(["inferenceProvider", "inferenceGatewayBaseUrl", "inferenceGatewayApiKey", "inferenceGatewayAuthScheme", "inferenceModels", "inferenceCustomHeaders", "modelDiscoveryEnabled"])],
@@ -172,7 +172,7 @@ export function reconcileClaudeConfiguration(operations, { restore = false, rest
172
172
  throw new Error("Claude configuration ownership is invalid; files were preserved");
173
173
  }
174
174
  const states = new Map(), pending = [], nextJournal = structuredClone(journal), skipped = [];
175
- const sharedOperation = op => op.file === paths.code && (op.keys[0] === "modelSettings" || ["CLAUDE_CODE_MAX_CONTEXT_TOKENS", "CLAUDE_CODE_MAX_OUTPUT_TOKENS", "CLAUDE_CODE_MODEL_CAPABILITIES"].includes(op.keys[1]));
175
+ const sharedOperation = op => op.file === paths.code && (op.keys[0] === "modelSettings" || ["CLAUDE_CODE_MAX_CONTEXT_TOKENS", "CLAUDE_CODE_MAX_OUTPUT_TOKENS", "CLAUDE_CODE_MODEL_CAPABILITIES", "CLAUDE_CODE_GATEWAY_HINT_HEADERS"].includes(op.keys[1]));
176
176
  const forClient = op => (!options.selectOperation || options.selectOperation(op)) && (!options.client || (options.client === "claude_code" ? op.file === paths.code && !sharedOperation(op) : op.file !== paths.code))
177
177
  && (!options.fields || options.fields.includes(op.keys.join(".")));
178
178
  const list = restore ? journal.operations.filter(forClient) : [
@@ -9,7 +9,7 @@ import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
9
9
  import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
10
10
  import { runWithRequestContext, currentRequestContext, observeRequestedModel } from "./request-context.mjs";
11
11
  import { upstreamErrorEvidence, requestOptionsEvidence } from "./response-failures.mjs";
12
- import { createStreamPerformanceMetrics, isMessagesOutputDelta, markRequestObservation } from "./stream-performance.mjs";
12
+ import { createStreamPerformanceMetrics, isMessagesOutputDelta, markRequestObservation, markToolActivity } from "./stream-performance.mjs";
13
13
  import { buildMessagesUsageRecord, recordUsage } from "./usage-store.mjs";
14
14
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
15
15
  import { decodedBodyLimitPreference } from "./user-settings.mjs";
@@ -20,6 +20,9 @@ import { catalogCapabilities } from "./model-capabilities.mjs";
20
20
  import { applyMessagesSystemPolicy } from "./messages-system-policy.mjs";
21
21
  import { createApiTokenCounter } from "./providers/api-token-count.mjs";
22
22
  import { MESSAGES_TOOL_GUARD } from "./messages-tool-schema.mjs";
23
+ import { isCompactionRequest, compactionScope } from "./context-compaction.mjs";
24
+ import { compactionSummarizer } from "./context-compaction-wire.mjs";
25
+ import { requestPurpose } from "./request-context.mjs";
23
26
 
24
27
  function observeMessagesWindow(provider, model, capability, entry) {
25
28
  try {
@@ -197,7 +200,7 @@ function createGuardedMessagesObserver(onEvent, maxBytes, clientModel, guard, re
197
200
  }
198
201
 
199
202
  export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, appContract, messagesSystemMode = "passthrough", log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
200
- resolveRequest, privacy, privacyClient = "claude", record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
203
+ resolveRequest, privacy, compaction, privacyClient = "claude", record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
201
204
  if (!provider || !isProviderId(provider.id) || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
202
205
  const config = loadRuntimeConfig(env), performance = sharedPerformance || createStreamPerformanceMetrics({ routeNames: ["messages"] });
203
206
  const decodedLimit = decodedBodyLimitPreference({ env }).bytes;
@@ -225,7 +228,9 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
225
228
  const parent = currentRequestContext();
226
229
  if (parent) parent.provider = provider.id;
227
230
  const countTokens = pathname.endsWith("/count_tokens"), requestId = parent?.requestId || randomUUID();
228
- const tracker = countTokens ? parent?.streamPerformance : performance.begin("messages", { requestId, purpose: req.headers["x-ccdx-purpose"], application: requestApplication(req.headers, "claude") });
231
+ const compacting = !countTokens && isCompactionRequest("messages", null, req.headers);
232
+ const purpose = requestPurpose(req.headers["x-ccdx-purpose"], compacting ? "compaction" : "conversation");
233
+ const tracker = countTokens ? parent?.streamPerformance : performance.begin("messages", { requestId, purpose, application: requestApplication(req.headers, "claude") });
229
234
  if (!resolveRequest) tracker?.setProvider(provider.id);
230
235
  const abort = createRequestAbort(req, res);
231
236
  let release = () => {}, conversation, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
@@ -233,6 +238,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
233
238
  let terminalOrigin = "client_validation", failureStatus = null, countDeadline = null, rejectionReason;
234
239
  if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
235
240
  const context = parent || { requestId, purpose: req.headers["x-ccdx-purpose"] };
241
+ if (!countTokens) context.purpose = purpose;
236
242
  context.provider = selectedProvider.id;context.application = requestApplication(req.headers, "claude");
237
243
  context.streamPerformance = tracker;context.route = countTokens ? "messages_count_tokens" : "messages";
238
244
  await runWithRequestContext(context, async () => {
@@ -242,6 +248,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
242
248
  let body = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: config.maxBodyBytes, maxDecodedBodyBytes: decodedLimit });
243
249
  abort.setTimeout(config.upstreamTimeoutMs, "messages_prepare_timeout");
244
250
  observeRequestedModel(body);
251
+ if (compacting) markRequestObservation({ compaction: 1 });
245
252
  context.requestOptions = requestOptionsEvidence(body);
246
253
  if (context.requestOptions.client_tool_errors_received) markRequestObservation({ client_tool_errors_received: context.requestOptions.client_tool_errors_received });
247
254
  if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
@@ -274,7 +281,15 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
274
281
  conversation = await validateConversation?.(body, req.headers, selectedProvider, abort.signal);
275
282
  if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
276
283
  terminalOrigin = "transport";
277
- const call = privacy?.wrap(selectedProvider.client.messages, { res, protocol: "messages", client: privacyClient }) || selectedProvider.client.messages;
284
+ const sourceCall = compacting && compaction ? (value, options) => {
285
+ let limits = selectedCapability?.values;
286
+ if (!limits) try { const entry = selectedModel || resolveClaudeModel(selectedProvider.models("claude"), value.model);limits = entry?.protocol_capabilities?.messages?.values || entry?.capability?.values || catalogCapabilities(entry || {}); } catch { limits = {}; }
287
+ return compaction.run({ body: value, protocol: "messages", scope: compactionScope(selectedProvider, privacyClient, "messages"), source: selectedProvider.id,
288
+ client: privacyClient, inputLimit: limits.max_input_tokens || limits.context_window, outputAllowance: value.max_tokens || 0,
289
+ native: selectedProvider.client.messages, options, summarize: compactionSummarizer(value, "messages", selectedProvider.client.messages),
290
+ onActivity: () => abort.setTimeout(config.streamIdleTimeoutMs, "compaction_idle_timeout") });
291
+ } : selectedProvider.client.messages;
292
+ const call = privacy?.wrap(sourceCall, { res, protocol: "messages", client: privacyClient }) || sourceCall;
278
293
  let upstreamHeadersObserved = false;
279
294
  const callOptions = { headers: req.headers, countTokens, signal: abort.signal,
280
295
  onUpstreamErrorHeaders(status) { upstreamHeadersObserved = true;tracker?.upstreamHeaders(status);body = null;release();release = () => {}; },
@@ -322,6 +337,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
322
337
  if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw, { status: upstream.status }),
323
338
  origin: context.countObservation?.cached ? "capability_cache" : "upstream_http", headers: upstream.headers });
324
339
  if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
340
+ markToolActivity(value, "messages");
325
341
  if (value.content.some(hasMessageState)) await conversation?.commit?.({ tool: value.content.some(block => block?.type === "tool_use") });
326
342
  abort.signal.throwIfAborted();
327
343
  model = value.model || model;responseId = value.id;usage = value.usage;stopReason = value.stop_reason;
@@ -348,6 +364,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
348
364
  context.onHttpError?.({ ...evidence, code: evidence.code || evidence.error_type || "upstream_error", model_error: true, origin: "upstream_event", headers: upstream.headers });return;
349
365
  }
350
366
  if (sawStop || failedEvent) return;
367
+ if (event.type === "content_block_start") markToolActivity(event, "messages");
351
368
  if (event.type === "content_block_start" && hasMessageState(event.content_block)
352
369
  || event.type === "content_block_delta" && (isMessagesOutputDelta(event.delta) || event.delta?.type === "signature_delta" && event.delta.signature)) {
353
370
  if (!conversationCommitted) commitState = { tool: commitState?.tool === true || event.content_block?.type === "tool_use" };
@@ -401,6 +418,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
401
418
  context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(rejectionReason ? { reason: rejectionReason } : {}), ...(diagnostic ? { transport: diagnostic } : {}) });
402
419
  if (outcome === "cancelled") return;
403
420
  if (!res.headersSent) {
421
+ if (typeof error.code === "string" && error.code.startsWith("ccdx_compaction_")) res.setHeader("x-should-retry", "false");
404
422
  if (error.origin === "privacy" && Number.isInteger(error.retryAfter) && error.retryAfter > 0) res.setHeader("Retry-After", String(error.retryAfter));
405
423
  const value = apiError(abort.reason || error.code || "ccdx_gateway_error", message);
406
424
  if (rejectionReason) value.error.reason = rejectionReason;