codex-copilot-dx 1.3.28 → 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 (43) hide show
  1. package/README.md +3 -1
  2. package/docs/ARCHITECTURE.md +17 -1
  3. package/docs/REFERENCE.md +25 -3
  4. package/package.json +1 -1
  5. package/src/adapter.mjs +13 -3
  6. package/src/antigravity-handler.mjs +38 -13
  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 +19 -3
  11. package/src/cli-command-spec.mjs +7 -3
  12. package/src/cli-management.mjs +21 -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 +1 -1
  21. package/src/conversation-source-guard.mjs +15 -5
  22. package/src/dashboard/index.html +7 -1
  23. package/src/dashboard/language.js +4 -0
  24. package/src/dashboard/preferences.js +1 -1
  25. package/src/http-transport.mjs +1 -1
  26. package/src/local-privacy.mjs +15 -7
  27. package/src/lock.mjs +9 -2
  28. package/src/privacy-detection.mjs +4 -3
  29. package/src/privacy-transform.mjs +20 -6
  30. package/src/provider-runtime.mjs +8 -5
  31. package/src/providers/api.mjs +15 -4
  32. package/src/request-context.mjs +1 -1
  33. package/src/responses-bridge.mjs +12 -5
  34. package/src/responses-handler.mjs +79 -1
  35. package/src/responses-proxy.mjs +18 -5
  36. package/src/responses-request.mjs +11 -4
  37. package/src/safe-upstream-error.mjs +29 -11
  38. package/src/service-control.mjs +8 -1
  39. package/src/settings-preferences.mjs +3 -3
  40. package/src/stream-performance.mjs +3 -2
  41. package/src/upstream-body.mjs +1 -1
  42. package/src/upstream-error-capture.mjs +29 -0
  43. package/src/user-settings.mjs +1 -1
package/README.md CHANGED
@@ -54,7 +54,9 @@ 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
+ | Capture one upstream error | `ccdx requests diagnose --source api_work --model model-id --yes` |
58
60
  | Read usage | `ccdx usage` / `ccdx usage --provider google --days 7` / `ccdx usage --purpose diagnostic` / `ccdx usage --scope run` |
59
61
  | Inspect preferences | `ccdx config show --effective` |
60
62
  | Inspect local masking | `ccdx config privacy status` |
@@ -62,7 +64,7 @@ Model availability depends on your account and service. Microsoft 365 also requi
62
64
 
63
65
  Use `ccdx help` or `ccdx <command> --help` for options. The CLI uses English; the Web UI supports English and Chinese.
64
66
 
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).
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).
66
68
 
67
69
  ## Features and maintenance
68
70
 
@@ -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,17 @@ 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.
package/docs/REFERENCE.md CHANGED
@@ -109,7 +109,7 @@ requests and check ordinary Gemini chat when accepting a new App version.
109
109
 
110
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.
111
111
 
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.
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.
113
113
 
114
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.
115
115
 
@@ -157,9 +157,27 @@ Model details can declare `max_tool_definitions` and `supported_parameters`. Cat
157
157
 
158
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
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
+
160
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.
161
163
 
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.
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.
163
181
 
164
182
  ## Microsoft 365
165
183
 
@@ -808,6 +826,8 @@ CLI/TUI, WebUI totals and daily analytics use the same paired evidence for cache
808
826
 
809
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.
810
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
+
811
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.
812
832
 
813
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.
@@ -933,6 +953,8 @@ Privacy failures have a separate local diagnostic origin. Response-restoration f
933
953
 
934
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.
935
955
 
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.
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.
937
957
 
938
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.28",
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
@@ -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";
@@ -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){
@@ -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) : [
@@ -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 = () => {}; },
@@ -401,6 +416,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
401
416
  context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(rejectionReason ? { reason: rejectionReason } : {}), ...(diagnostic ? { transport: diagnostic } : {}) });
402
417
  if (outcome === "cancelled") return;
403
418
  if (!res.headersSent) {
419
+ if (typeof error.code === "string" && error.code.startsWith("ccdx_compaction_")) res.setHeader("x-should-retry", "false");
404
420
  if (error.origin === "privacy" && Number.isInteger(error.retryAfter) && error.retryAfter > 0) res.setHeader("Retry-After", String(error.retryAfter));
405
421
  const value = apiError(abort.reason || error.code || "ccdx_gateway_error", message);
406
422
  if (rejectionReason) value.error.reason = rejectionReason;
@@ -183,6 +183,10 @@ export const MANAGED_COMMANDS = [
183
183
  "--limit": "integer",
184
184
  }),
185
185
  command("requests show <request>", "Show a retained request and its original diagnostic fields", read),
186
+ command("requests diagnose", "Capture one redacted upstream Messages error; expires after ten minutes", { ...read, ...confirm, "--source": "value", "--model": "value", "--cancel": "flag" }),
187
+ command("compact status", "Show native and gateway compression observations without model calls", read),
188
+ command("compact enable", "Enable bounded recovery using the current source and model; uses quota", { ...read, ...confirm }),
189
+ command("compact disable", "Disable gateway compression fallback while keeping native compression", { ...read, ...confirm }),
186
190
  command("status", "Show service state; expand diagnostics explicitly", { ...read, "--details": "flag" }),
187
191
  command("usage", "Show all recorded usage or this service run", {
188
192
  ...read,
@@ -231,7 +235,7 @@ function optionsFor(args, definition) {
231
235
  if (type === "format" && !["table", "plain", "json"].includes(value))
232
236
  throw new Error("Format must be table, plain or json");
233
237
  if (type === "scope" && !["run", "all"].includes(value)) throw new Error("Scope must be run or all");
234
- if (type === "purpose" && !["conversation", "diagnostic", "compatibility", "unknown"].includes(value)) throw new Error("Purpose must be conversation, diagnostic, compatibility or unknown");
238
+ if (type === "purpose" && !["conversation", "compaction", "diagnostic", "compatibility", "unknown"].includes(value)) throw new Error("Purpose must be conversation, compaction, diagnostic, compatibility or unknown");
235
239
  if (type === "integer" && (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 100))
236
240
  throw new Error("Limit must be an integer from 1 to 100");
237
241
  values[key] = type === "integer" ? Number(value) : value;
@@ -291,7 +295,7 @@ const extras = {
291
295
  status:
292
296
  "Default interactive status is brief; --details retains the complete diagnostic view.\nThe installed package version can differ from the running service.\nA listening gateway does not prove upstream model access.",
293
297
  usage:
294
- "Default usage includes all recorded usage. Filter it with --provider, --model, --purpose and --days 1..365|all, or --from/--to YYYY-MM-DD.\nPurpose: conversation, diagnostic, compatibility or unknown. Older records without a purpose remain unknown; every purpose stays in default totals.\nDates use --time-zone (UTC by default). Source-qualified models use 'source / model'.\n--scope run reads the running service and supports only --provider.\nGemini usage includes Antigravity Copilot and native Google responses. Missing upstream counts stay unknown; historical missing usage is not reconstructed.\nUsage records are not billed request counts. Cache hit is a token-reuse estimate.",
298
+ "Default usage includes all recorded usage. Filter it with --provider, --model, --purpose and --days 1..365|all, or --from/--to YYYY-MM-DD.\nPurpose: conversation, compaction, diagnostic, compatibility or unknown. Older records without a purpose remain unknown; every purpose stays in default totals.\nDates use --time-zone (UTC by default). Source-qualified models use 'source / model'.\n--scope run reads the running service and supports only --provider.\nGemini usage includes Antigravity Copilot and native Google responses. Missing upstream counts stay unknown; historical missing usage is not reconstructed.\nUsage records are not billed request counts. Cache hit is a token-reuse estimate.",
295
299
  doctor:
296
300
  "Default checks are read-only. Explicit online/compatibility checks and owned repairs have separate options.",
297
301
  update:
@@ -331,5 +335,5 @@ export function managedCommandHelp(parts) {
331
335
  );
332
336
  }
333
337
  export function rootCommandHelp() {
334
- return `Usage:\n ccdx [start] [--show-request-id] [--no-browser] [--verbose]\n\nCommon:\n status Show service state; --details expands diagnostics\n web Open local management tools\n requests Show retained model requests and failures\n usage Show recorded token usage\n doctor Check local setup; deeper checks are explicit\n\nManage:\n source Accounts, APIs, catalogs and client authorization\n app Client model plans, sync and app-specific features\n config Service and terminal preferences\n\nUpdate:\n update check Check without installing\n update github|npm Install; restart the service normally afterward\n version Show installed package version\n\nHelp:\n ccdx <command> --help\n ccdx help app codex prediction\n\nStart keeps the existing configured-client setup and launch behavior.\nCLI output stays in English. Read-only commands do not start a service.`;
338
+ return `Usage:\n ccdx [start] [--show-request-id] [--no-browser] [--verbose]\n\nCommon:\n status Show service state; --details expands diagnostics\n web Open local management tools\n requests Show retained model requests and failures\n usage Show recorded token usage\n compact Inspect and control context compression\n doctor Check local setup; deeper checks are explicit\n\nManage:\n source Accounts, APIs, catalogs and client authorization\n app Client model plans, sync and app-specific features\n config Service and terminal preferences\n\nUpdate:\n update check Check without installing\n update github|npm Install; restart the service normally afterward\n version Show installed package version\n\nHelp:\n ccdx <command> --help\n ccdx help app codex prediction\n\nStart keeps the existing configured-client setup and launch behavior.\nCLI output stays in English. Read-only commands do not start a service.`;
335
339
  }
@@ -111,7 +111,28 @@ export async function runManagementCommand(command, options = {}) {
111
111
  ...(sourceNames ? [sourceNames] : []), "", print(view.clients, [["name", "Client"], ["setup", "Setup"], ["active", "Active"]]), "",
112
112
  `Model requests: ${view.requests ?? "unknown"} total · ${view.active ?? "unknown"} active · ${view.outcomes.failed} failed`].join("\n");
113
113
  }
114
+ if (group === "compact") {
115
+ const live = await request({ path: "settings" });
116
+ if (action === "status") return print(live.compaction || { enabled: false, state: "unsupported" });
117
+ if (!live.compaction) throw new Error("This command needs the updated running service; no settings changed.");
118
+ const enabled = action === "enable";
119
+ if (flags.preview) return print({ enabled, saved: false, source_policy: "current source and model", uses_quota: enabled });
120
+ await confirm(enabled ? "Enable bounded compression recovery using the current source and model? It can use quota." : "Disable gateway compression fallback?");
121
+ const result = await request({ path: "settings", body: { action: "preference", key: "context_compaction_enabled", value: enabled } });
122
+ return print(result.compaction);
123
+ }
114
124
  if (group === "requests") {
125
+ if (action === "diagnose") {
126
+ if (flags.source || flags.model || flags.cancel) {
127
+ if (!flags.cancel && (!flags.source || !flags.model)) throw new Error("Use --source ID and --model ID together.");
128
+ if (flags.cancel && (flags.source || flags.model)) throw new Error("Use --cancel alone.");
129
+ if (flags.preview) return print({ source: flags.source, model: flags.model, operation: flags.cancel ? "cancel" : "arm", saved: false, error_limit: 512, expires_minutes: 10 });
130
+ await confirm(flags.cancel ? "Cancel the pending capture?" : "Capture one redacted technical error (up to 512 characters)? It may contain a request fragment; no prompt body is saved.");
131
+ const result = await request({ path: "settings", body: { action: "error_capture", operation: flags.cancel ? "cancel" : "arm", ...(flags.cancel ? {} : { source: flags.source, model: flags.model }) } });
132
+ return print(result.error_capture);
133
+ }
134
+ return print((await request({ path: "settings" })).error_capture || { state: "unsupported" });
135
+ }
115
136
  let rows = retainedRequests((await readStatus()).data);
116
137
  if (ids.request) {
117
138
  const found = rows.find(row => row.request_id === ids.request);if (!found) throw new Error("Request not retained. No full-history lookup is available.");return print(found);
@@ -20,7 +20,7 @@ export function parseCliArgs(input = []) {
20
20
  throw new Error(`Unknown help topic: ${help.join(" ")}`);
21
21
  return base({ command: "help", helpTopic: help.join(" ") });
22
22
  }
23
- if (["app", "config", "source"].includes(args[0]) && args.length === 1)
23
+ if (["app", "config", "source", "compact"].includes(args[0]) && args.length === 1)
24
24
  return base({ command: "help", helpTopic: args[0] });
25
25
  const parsed = parseManagedCommand(args);
26
26
  return base(parsed.dispatch || parsed);
@@ -147,6 +147,7 @@ export function createConnectionRouting({ legacy, legacyClaudeAccess, isManaged,
147
147
  acquireRequest: acquireClaudeRequest,
148
148
  apiKey: identities()[id],
149
149
  privacy,
150
+ compaction: legacy.compaction,
150
151
  privacyClient: id,
151
152
  env,
152
153
  log,