codex-copilot-dx 1.4.3 → 1.4.5

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 (66) hide show
  1. package/README.md +4 -1
  2. package/bin/cli.mjs +5 -4
  3. package/docs/ARCHITECTURE.md +20 -0
  4. package/docs/REFERENCE.md +42 -8
  5. package/package.json +1 -1
  6. package/src/access-settings.mjs +5 -2
  7. package/src/adapter.mjs +9 -1
  8. package/src/antigravity-chat-bridge.mjs +4 -2
  9. package/src/antigravity-handler.mjs +51 -24
  10. package/src/antigravity-images.mjs +3 -2
  11. package/src/antigravity-runtime.mjs +13 -3
  12. package/src/application-configuration.mjs +43 -0
  13. package/src/application-control.mjs +114 -0
  14. package/src/application-evidence.mjs +42 -0
  15. package/src/application-process.mjs +114 -0
  16. package/src/claude-gateway.mjs +30 -17
  17. package/src/cli-command-spec.mjs +7 -4
  18. package/src/cli-management.mjs +37 -4
  19. package/src/client-effort.mjs +28 -0
  20. package/src/client-model-plan.mjs +2 -1
  21. package/src/codex-image-host-launch.mjs +1 -2
  22. package/src/codex-launch-control.mjs +7 -7
  23. package/src/connection-management.mjs +18 -3
  24. package/src/connection-policy.mjs +9 -1
  25. package/src/connection-routing.mjs +8 -2
  26. package/src/connection-runtime.mjs +21 -5
  27. package/src/connection-view.mjs +12 -3
  28. package/src/context-compaction-wire.mjs +7 -6
  29. package/src/context-compaction.mjs +6 -4
  30. package/src/copilot-client.mjs +17 -13
  31. package/src/copilot-responses-compat.mjs +1 -0
  32. package/src/copilot-web.mjs +6 -2
  33. package/src/dashboard/applications.js +83 -0
  34. package/src/dashboard/connections.js +71 -18
  35. package/src/dashboard/console.js +19 -9
  36. package/src/dashboard/gemini.js +8 -5
  37. package/src/dashboard/index.html +17 -0
  38. package/src/dashboard/language.js +45 -0
  39. package/src/dashboard/ui.css +9 -0
  40. package/src/dashboard-api.mjs +6 -1
  41. package/src/dashboard.mjs +1 -0
  42. package/src/gemini-app.mjs +3 -2
  43. package/src/http-transport.mjs +6 -3
  44. package/src/launcher.mjs +6 -5
  45. package/src/native-images.mjs +1 -1
  46. package/src/provider-runtime.mjs +14 -9
  47. package/src/providers/api.mjs +18 -12
  48. package/src/providers/m365.mjs +9 -5
  49. package/src/request-admission.mjs +6 -0
  50. package/src/responses-bridge.mjs +5 -2
  51. package/src/responses-handler.mjs +2 -0
  52. package/src/responses-proxy.mjs +9 -4
  53. package/src/safe-upstream-error.mjs +9 -11
  54. package/src/service-control.mjs +29 -5
  55. package/src/settings-preferences.mjs +3 -3
  56. package/src/source-admission-state.mjs +29 -0
  57. package/src/source-admission.mjs +310 -0
  58. package/src/source-discovery-probe.mjs +35 -0
  59. package/src/source-discovery.mjs +112 -0
  60. package/src/source-response.mjs +134 -0
  61. package/src/source-transport.mjs +19 -0
  62. package/src/stream-contract.mjs +3 -1
  63. package/src/stream-performance.mjs +3 -1
  64. package/src/stream.mjs +6 -4
  65. package/src/upstream-body.mjs +9 -8
  66. package/src/user-settings.mjs +2 -2
package/README.md CHANGED
@@ -6,6 +6,8 @@ On macOS, the optional Gemini integration adds compatible Copilot Gemini models
6
6
 
7
7
  Connect GitHub Copilot, Microsoft 365 or your own API. Choose which apps can use each source, then select their models. CI and prebuilt releases cover **macOS on Apple Silicon** and **Windows on x64/ARM64**. Intel Mac code remains available, without CI coverage or new prebuilt assets.
8
8
 
9
+ Claude App keeps its native reasoning menu when it can represent the source's levels exactly. Otherwise, choose a declared fallback level in CCDX. It applies only when the App omits a level; model names and existing client choices stay unchanged.
10
+
9
11
  Optional local masking is off by default. Enable it in Settings → Local masking to download the model and component. Checks run locally and may add delay or mistake ordinary text; an unfinished check holds the request back. See [local masking](docs/REFERENCE.md#local-masking).
10
12
 
11
13
  ## Install and start
@@ -49,6 +51,7 @@ Model availability depends on your account and service. Microsoft 365 also requi
49
51
  | Open the Web UI | `ccdx web` |
50
52
  | Check service and apps | `ccdx status` / `ccdx app list` |
51
53
  | Preview imported APIs | `ccdx source import --file providers.json` |
54
+ | Find configured APIs in another tool | `ccdx source import --from cc-switch` or `--from magpie` |
52
55
  | Manage sources | `ccdx source list` / `ccdx source add` |
53
56
  | Sign in again | `ccdx source github reauth` |
54
57
  | Choose client models | `ccdx app codex models --edit` |
@@ -70,7 +73,7 @@ Use `ccdx help` or `ccdx <command> --help` for options. The CLI uses English; th
70
73
 
71
74
  ## Features and maintenance
72
75
 
73
- Start CCDX to open Codex with native image tools, then use a new chat. If image access is missing, use the Web UI image checks or `ccdx app codex image check`, `repair` and `open`. Running Apps are never forcibly restarted.
76
+ Open Codex from its Web UI page to use native image tools, then use a new chat. Automatic opening when CCDX starts is off by default. If image access is missing, use the Web UI image checks or `ccdx app codex image check`, `repair` and `open`. Running Apps are never forcibly restarted.
74
77
 
75
78
  Use the Web UI for accounts, APIs, models, client access, input suggestions, native images, local masking, appearance, diagnostics and updates. CLI commands remain available for automation and recovery. See the [control reference](docs/REFERENCE.md#webui-and-cli-controls).
76
79
 
package/bin/cli.mjs CHANGED
@@ -274,7 +274,7 @@ if (CLI.command === "start" && !(process.send && process.env.CCDX_SUPERVISED_SER
274
274
  }
275
275
 
276
276
  // Startup components are loaded only after read-only and local tool commands exit.
277
- const { ensureAuth, openCodex } = await import("../src/launcher.mjs");
277
+ const { ensureAuth, openCodex, autoLaunchEnabled } = await import("../src/launcher.mjs");
278
278
  const { startAdapter } = await import("../src/adapter.mjs");
279
279
  const { defaultCopilotClient, refreshVSCodeVersion } = await import("../src/copilot.mjs");
280
280
  const { configureLogging } = await import("../src/log.mjs");
@@ -402,7 +402,7 @@ async function reuseRunningAdapterIfAvailable() {
402
402
  if (!predictionPacUrl) console.warn(status("warn", "Restart ccdx to activate the newly enabled prediction bridge"));
403
403
  }
404
404
  } catch (error) { console.warn(status("warn", error.message)); }
405
- const imageHost = codexEnabled && imageEnabled ? await (await clientIntegrations()).imageHostLaunch() : null;
405
+ const imageHost = codexEnabled && imageEnabled && autoLaunchEnabled() ? await (await clientIntegrations()).imageHostLaunch() : null;
406
406
  if (codexEnabled) await openCodex({ predictionPacUrl, predictionApp, predictionProfile, persistedPredictionRoute, imageHost,
407
407
  onPredictionRoute: route => { launchRoute = route; }, log: startupLogger("App") });
408
408
  console.log(predictionStartupCheck({ configured: predictionConfigured, bridge: predictionPacUrl ? "running" : "unknown", launch_route: launchRoute }));
@@ -480,6 +480,7 @@ try {
480
480
  log: (kind, message) => console.log(startupComplete ? status(kind, message) : startupCheck(kind, "Models", message)),
481
481
  });
482
482
  providerRuntime = createProviderRuntime({ githubClient: profileRuntime.codexClient, githubRegistry: profileModels.codexRegistry,
483
+ persistSourceState: true,
483
484
  refreshGithubCatalog: () => profileModels.refreshCodex({ strict: true }),
484
485
  corePort: ADAPTER_PORT, preserveClientConfiguration: () => serviceWorker?.preserving === true || serviceWorker?.draining === true,
485
486
  clientVersionsSnapshot: clientVersions.snapshot,
@@ -533,7 +534,7 @@ try {
533
534
  activeServer = await startAdapter(serviceWorker?.warming ? 0 : ADAPTER_PORT, serviceWorker?.warming ? "127.0.0.1" : ADAPTER_HOST, {
534
535
  log: startupLogger("Service"),
535
536
  autoReviewModelResolver: () => autoReviewPreference(),
536
- codexClient: profileRuntime.codexClient,
537
+ codexClient: providerRuntime.source("github").client,
537
538
  codexModelCatalog,
538
539
  codexModelRegistry: profileModels.codexRegistry,
539
540
  providerRuntime,
@@ -560,7 +561,7 @@ try {
560
561
  const persistentRoute = await nativePrediction?.prepareRoute();
561
562
 
562
563
  // Launch Codex when available. A running App is never forcibly restarted.
563
- const imageHost = codexEnabled && imageEnabled ? await clientIntegration.imageHostLaunch() : null;
564
+ const imageHost = codexEnabled && imageEnabled && autoLaunchEnabled() ? await clientIntegration.imageHostLaunch() : null;
564
565
  if (codexEnabled) await openCodex({ predictionPacUrl: nativePrediction?.pacUrl, predictionApp: nativePrediction?.app, predictionProfile: nativePrediction?.profile, imageHost,
565
566
  preparePredictionRoute: () => nativePrediction?.prepareRoute(), persistedPredictionRoute: persistentRoute?.status === "installed",
566
567
  onPredictionRoute: route => clientIntegration?.launched(route), log: startupLogger("App") });
@@ -51,6 +51,20 @@ No independent WebKit client or private WebKit SPI is included.
51
51
 
52
52
  ## Composition and lifecycle
53
53
 
54
+ ### Application control and shared source admission
55
+
56
+ `application-process.mjs` discovers verified desktop identities and reads PID/start-time and scoped loopback socket metadata. `application-configuration.mjs` asynchronously reads bounded integration fields and computes semantic in-memory revisions; inspection never writes application files. `application-evidence.mjs` retains bounded accepted protocol metadata and joins it to the current process family. An open socket by itself cannot establish adoption. Evidence expires after five minutes, and process/configuration changes invalidate it. `application-control.mjs` caches a shared process inventory for three seconds, bounds inspection, serializes explicit control actions and uses graceful exits only. The Web UI keeps newer inspection results when ordinary settings snapshots arrive late. Antigravity header and legacy launch controls share this controller, busy state and process evidence. Verified system and home Applications installations use the same path and signature checks. Claude Code remains a terminal process outside desktop launch control.
57
+
58
+ Automatic Codex opening uses the saved `codex_auto_launch` preference, default false, with explicit launch-environment precedence. Manual preparation and opening do not depend on that preference. Existing field-owned sync/restore modules retain configuration ownership; image/suggestion capabilities keep their own evidence boundaries. No App bundle patching, account changes or inference probes are added.
59
+
60
+ `source-admission.mjs` wraps each provider client once and shares account-scoped leases across Responses, Messages, Chat, Images and relevant search/native-Google calls. HTTP providers enter admission after final serialization and reuse that wire text for queued-byte accounting and sending. Upstream timing starts at dispatch, after the queue. Internal consumers settle ownership in their existing read, error and cancellation callbacks through `source-response.mjs`, retaining native Responses without another stream or facade. Unmanaged clients keep the compatibility wrapper. Lease ownership ends at upstream-body completion/cancellation, not response headers. Counting/catalog reads bypass generation admission. Request-body memory reservations remain separate and shrink only after a complete upload; compressed decoded-body accounting remains intact. Rejected response bodies release their leases before nested recovery calls, with a bounded release barrier for compaction.
61
+
62
+ Raw HTTP 429 responses without private classified evidence receive a bounded clone read before being returned, so feedback does not depend on a caller retaining the error body. The original response remains available. A timed-out inspection retains body-consumption fallback; successful classification is not repeated and Retry-After stays anchored to the response arrival. Real upstream EOF on any clone releases the source slot; cancelling only one clone does not. Unchanged request-body reservations do not drain their queue again.
63
+
64
+ Explicit concurrency rejections contract once per observed burst. Stable success retains growth eligibility through idle periods; waiting demand then grows capacity additively. Persistence notifications remain throttled separately. Model quota/rate evidence and explicit account-wide evidence keep separate scopes. Ordinary parameter errors, slow thinking and untyped output text do not train capacity. HTTP 200 stream errors enter feedback only through existing structured protocol parsers. API providers pass a private fixed-field Symbol through safe error projection; original vendor text is never persisted. Queue limits are 16 per account, 8 MiB globally and 30 seconds; the initial 128-slot ceiling preserves the existing small held-stream workload and is not an upstream capacity claim. A manual source ceiling is optional. Stable capacity persistence is asynchronous, bounded and keyed by hashes; invalid or stale metadata is discarded.
65
+
66
+ The upstream references are deliberately narrow: [Floway's model-scoped quota correction](https://github.com/Menci/Floway/commit/49813611aac1f7d0cccb10cfd343c1df7541790e) and [single Chat output cap](https://github.com/Menci/Floway/commit/63f1100af6bc2823e7f0f478fbd785aa56dc0cd7), [Magpie's quota/compaction boundary](https://github.com/yetone/magpie/issues/2725), and [LiteLLM's disconnect outcome report](https://github.com/BerriAI/litellm/issues/51978). CCDX preserves an already observed terminal result while marking delivery cancellation separately; an unfinished stream is not promoted to success. The existing CC Switch-style separation of configuration, discovery and application activation is retained. No upstream runtime, distributed queue or automatic account rotation is introduced.
67
+
54
68
  ### Manual connection graph
55
69
 
56
70
  `provider-runtime.mjs` composes built-in lifecycle with `connection-runtime.mjs`,
@@ -68,6 +82,8 @@ A cancelled caller releases its wait independently; a late shared result cannot
68
82
  resume its request. Messages keeps body upload, preparation and upstream budgets
69
83
  separate using the existing request-abort boundary.
70
84
 
85
+ Explicit source import can discover known CC Switch/Magpie configuration through `source-discovery.mjs`. It is dynamically loaded by the control plane, not by inference dispatch. `source-discovery-probe.mjs` reads and parses JSON/SQLite separately, returns sanitized drafts through the existing import validator, then exits. The service shares identical reads and permits at most two pending discovery tasks, each bounded to five seconds. The helper uses read-only SQLite, a short busy timeout and fixed projected queries; it does not migrate, checkpoint, copy or repair foreign stores. Directory overrides and normal live WAL reads are retained. Output contains no foreign key, permission, command, route alias or account policy. File import remains independent. The minimum implementation follows the mechanism of [CC Switch discovery](https://github.com/BigPizzaV3/ClaudeMom/blob/cd5e69a7b654f7191b0d96ae1ebc306929d9254e/apps/claude-mom/src-tauri/src/upstreams.rs), with independently implemented multi-protocol projection and CCDX's existing private-key/grant boundaries.
86
+
71
87
  `model-capabilities.mjs` owns neutral limits, reasoning/tool/input/search fields,
72
88
  strict manual values, per-field evidence and deployment revisions. It reads no
73
89
  credentials or client files. Explicit manual values override the current API's
@@ -700,6 +716,8 @@ left unchanged. Ordinary accepted requests and streams bypass this adaptation.
700
716
 
701
717
  Byte-weighted request admission is not a simultaneous-stream limit. The 1.2.0 load replay exercises 16/64/128 small-body held streams, management responsiveness and downstream cancellation against 1.1.1. It does not establish a universal safe concurrency maximum. Existing defaults remain unchanged; see the release receipt for measured bounds.
702
718
 
719
+ Antigravity retains its shared body reservation while reading, decoding, masking and performing compaction recovery. Once the final upstream response opens, it drops the native request, converted Chat payload and privacy-session body references before releasing both raw and decoded reservations. Response restoration mappings remain alive until completion or cancellation. Search and image operations retain their input reservation through completion. Queue waiting uses the admission deadline; the body deadline starts only after admission. Admission/body preparation timings and fixed abort codes distinguish local queue failures (`503`), body deadlines (`408`), upstream or compaction deadlines (`504`) and client cancellation (`499`), without changing budgets, queue fairness or product timeouts.
720
+
703
721
  ## Installation and release delivery
704
722
 
705
723
  `release-install.mjs` is a standalone helper with built-in static imports, shared by the updater
@@ -1177,6 +1195,8 @@ The 1.3.13 native helper groups uncached short CPU sequences under the existing
1177
1195
 
1178
1196
  `claude-app-contract.mjs` reads bounded installed macOS archive declarations and consumers, extracts native effort profiles, and caches by installation identity. Lightweight file hints and the existing refresh path coalesce revalidation outside inference. `connection-runtime.mjs` replaces the capability snapshot and clears compiled plans before owned synchronization. Profile entries and discovery replies carry identical `behavesAs`/`behaves_as` and effort caps. Neutral route identity stays source-qualified; previously published aliases remain resolvable. Legacy inspected adapters remain available when a newer native contract cannot be checked. Non-contiguous effort sets are declared as limited instead of remapped. Shared capability-map reconciliation preserves manual entries and unchanged original restoration state. Native profile loading may require a normal client restart; requested and sent effort observations do not establish unobserved picker adoption.
1179
1197
 
1198
+ `client-effort.mjs` separates declared source effort sets from native menu presentation. Exact native contracts remain preferred; otherwise the existing client-model form offers source-declared values without model-name cases or level remapping. The optional Claude App deployment `reasoning_effort` is compiled into an internal route-record default, not native model metadata or provider configuration. Authenticated client/source/model resolution pins it with the capability snapshot. The gateway shallow-copies only a generation request missing `output_config.effort`, preserving its history and output-format fields. Explicit App values retain the existing validation path. Count-token requests and other clients never receive the default. Removed defaults remain configured for correction and fail before forwarding when needed. Drafts, revisions, source isolation and Save/Discard retain their existing boundaries. App inspection remains read-only; the signed model-catalog channel, binaries, trust roots, session-host mode and tool permissions are not changed.
1199
+
1180
1200
  Usage presentation maps configured api_ identifiers to current provider labels after aggregation. Rows, chart filters and historical statistics keep their original keys. Provider-label changes refresh only the table/model labels, preserving the selected raw model key, day and existing chart nodes. The native capability replay disables usage persistence and gives its process a temporary usage path; no production filter recognizes test model names or response IDs.
1181
1201
 
1182
1202
  ## Native image recovery and request correlation
package/docs/REFERENCE.md CHANGED
@@ -12,11 +12,13 @@ For installation and first use, start with the [README](../README.md). This refe
12
12
  | `ccdx web` | Open the Web UI, or start management without signing in |
13
13
  | `ccdx status` | Show runtime and app configuration; `--details` expands diagnostics |
14
14
  | `ccdx source import --file FILE [--select N --apply --key-stdin --yes]` | Preview API metadata; explicitly save one source without client grants |
15
+ | `ccdx source import --from cc-switch\|magpie` | Find local API configuration and preview it without saving |
15
16
  | `ccdx source list` / `source add` | List sources or add an API |
16
17
  | `ccdx source <id> status` | Read saved account and catalog evidence |
17
18
  | `ccdx source <id> models [--refresh]` | Read cached models, or explicitly refresh the source |
18
19
  | `ccdx source <id> check` | Check source access without inference |
19
20
  | `ccdx source <id> access --edit` | Choose allowed apps |
21
+ | `ccdx source <id> limits [--max auto\|N] [--edit]` | Read automatic concurrency or set a ceiling |
20
22
  | `ccdx source <id> enable` / `disable` | Change source access; disabling reviews affected apps |
21
23
  | `ccdx source <id> edit` / `remove` | Edit an API, or remove a disabled, unbound API |
22
24
  | `ccdx source github login` / `reauth` / `logout` | Manage the saved GitHub account |
@@ -26,6 +28,8 @@ For installation and first use, start with the [README](../README.md). This refe
26
28
  | `ccdx app <id> models --edit` | Choose visible models and a default |
27
29
  | `ccdx app <id> sync --preview` | Preview the model/configuration plan |
28
30
  | `ccdx app <id> sync` | Write client settings owned by CCDX |
31
+ | `ccdx app <id> check` | Check the current desktop process and owned configuration without inference |
32
+ | `ccdx app <id> open` / `focus` / `restart` | Open or focus the desktop App; reopening requires confirmation |
29
33
  | `ccdx app <id> enable` / `disable` | Change access without quitting the app |
30
34
  | `ccdx app codex prediction …` | Native suggestion setup and diagnostics |
31
35
  | `ccdx app codex image …` | Native image controls and model selection |
@@ -50,12 +54,20 @@ For installation and first use, start with the [README](../README.md). This refe
50
54
 
51
55
  Client IDs are `codex`, `claude-app` and `claude-code`. Source IDs are listed by `source list`. Read-only management commands support `--format table|plain|json`. They do not start an app or a gateway. Native image/suggestion status also reads local setup when the gateway is stopped; JSON includes the saved configuration flag and the same public details. Management operations need the running service; use `ccdx web` to start it without launching a client.
52
56
 
57
+ The Codex, Claude App and Antigravity pages have a primary **Open app** action. A running App is focused, not launched again. **Reopen** requires confirmation and requests a normal exit; refusal, a changed process or multiple matching Apps stops the operation. Current desktop control covers macOS Codex, Claude App and Gemini/Antigravity, plus registered Codex and Claude installations on Windows. Claude Code remains a terminal client.
58
+
59
+ **Open Codex when CCDX starts** is off by default. It takes effect on the next service start. `CCDX_AUTO_LAUNCH` explicitly overrides the saved preference; `0` disables and `1` enables it. `ccdx config set codex_auto_launch true --yes` also enables it. Explicit image preparation and opening remain available with automatic opening disabled.
60
+
61
+ App checks read bounded integration fields, verified bundle/package identity, PID, start time and scoped loopback socket metadata. A live TCP connection alone never confirms adoption. CCDX correlates accepted existing catalog, control or inference traffic with the current process family. No synthetic model request, App restart, environment dump or binary modification is used. **Connection unconfirmed** includes inaccessible metadata or a quiet process; it does not mean a failed request. Confirmation covers only the observed local route, not every feature or model. Evidence expires after five minutes and resets after a process or relevant configuration change. Read-only checks never activate configuration. Explicit opening/sync retains field ownership and the saved automatic-sync choice.
62
+
53
63
  `start` supports `--no-browser`, `--verbose` and `--show-request-id`. The normal TUI has one source summary and one app table. It labels the Web UI address directly. `Unchanged` means existing client settings were kept; `Configured` means the configuration write/check succeeded. Neither is proof that a client process has loaded that configuration. Warnings and sign-in instructions remain visible during startup. The final activity row reflects observed model work. Ctrl+C stops the foreground service.
54
64
 
55
65
  For scripts, source access accepts `--apps codex,claude-app` with `--edit`; edits use confirmation or `--yes`. API/model edits accept `--file`. An API key uses the private prompt, `--key-stdin`, or an environment reference, never a command argument or metadata file. Source removal requires a disabled API with no client binding. Disabling an in-use source requires explicit replacement choices in scripts; `--yes` alone does not choose them.
56
66
 
57
67
  An app model file contains `deployments: [{"source":"github","model":"<model-id>"}]`, with optional `default_model` and `auto_sync`. An explicit empty array clears the default and pauses access. A file without `deployments` is rejected. Unavailable saved selections remain visible until the user changes them.
58
68
 
69
+ Claude App deployments may also specify `reasoning_effort`, for example `{"source":"api_work","model":"reasoner","reasoning_effort":"xhigh"}`. Omit it to follow the App. A client can send an automatic level even without a visible selection; CCDX preserves that supplied value. The fallback applies only when the request omits the field. `app claude-app models --edit` and the TUI expose the source's declared choices for models needing CCDX control, and preserve existing defaults during other model edits. This preference belongs to that client's source/model binding, not to the source shared with Codex or Claude Code.
70
+
59
71
  ## Antigravity in Gemini App
60
72
 
61
73
  The **Antigravity** page and `ccdx app antigravity status|models|enable|disable|open`
@@ -90,10 +102,10 @@ error rather than successful completion.
90
102
 
91
103
  This Copilot selection does not restrict Antigravity's original Google model directory. Google wire IDs such as `gemini-3.8-flash-tiered` can therefore appear in usage without being CCDX-added model choices. The recorded provider distinguishes Google and GitHub Copilot; the ID alone does not establish a background task or a fallback. Known conversation compaction retains its observed source and model.
92
104
 
93
- `enable` saves CCDX settings and prepares its local source guard. `open --preview` shows the launch plan.
94
- `open` starts a closed, signed `/Applications/Gemini.app` with a process-local
95
- Antigravity endpoint. An already running App is kept open and must be quit by
96
- the user before reopening. Existing gateway environment settings cause a
105
+ `enable` saves CCDX settings and prepares its local source guard. `open --preview` shows the inspected application state without launching it.
106
+ `open` starts a closed, verified Gemini App in `/Applications` or `~/Applications` with a process-local
107
+ Antigravity endpoint. An already running App is focused. Reopen requests a normal
108
+ exit after confirmation, through the same controller used by the page header. Existing gateway environment settings cause a
97
109
  conflict instead of being overwritten. The Gemini bundle, Google credentials,
98
110
  global proxy and certificates are untouched. Endpoint adoption remains
99
111
  unconfirmed until an Antigravity request is observed.
@@ -159,10 +171,20 @@ Verified newer contracts keep stable source-qualified model IDs. Both the native
159
171
 
160
172
  Capability declarations, successful synchronization and an observed outgoing effort are separate facts. `ccdx app claude-app status --details`, sync preview and retained request details expose these facts. A missing effort on one request is not proof of missing support. An unverified contract preserves affected existing settings. A non-contiguous set such as low/high/max stays declared and is reported as limited when the native picker cannot express it exactly; CCDX does not invent an intermediate level or silently remap the selection.
161
173
 
174
+ CCDX renders the complete declared set independently of the native menu. When the current verified App contract can express the exact set, the existing native presentation stays in use. Otherwise, the Reasoning cell provides a native-styled CCDX selector, such as `low / high / xhigh`, without adding a missing `medium` or creating model variants. An unknown App contract can still use this CCDX-side control when source capabilities are known. Refresh and navigation keep the draft; Save and Discard use the existing form.
175
+
176
+ A saved fallback is applied as Messages `output_config.effort` only when the App omits that field. Effort and thinking mode stay separate; the gateway does not enable, disable or rewrite `thinking`. Explicit App values are retained and pass through the existing capability validation; unsupported values are never mapped to nearby levels. Existing output-format fields, model IDs, history and tool permissions are preserved. Count-token requests and other clients do not receive the fallback. If the source stops advertising the saved level, the value remains visible as unavailable and generation needing that default fails with `ccdx_client_effort_unavailable` until it is corrected or cleared. Native configuration synchronization remains independent of this request preference; changing the preference does not add native model metadata or require an App restart for the parameter itself.
177
+
162
178
  ## API import and request validation
163
179
 
164
180
  **Model sources → Import** and `ccdx source import --file FILE` preview explicitly supplied JSON. Supported shapes are CCDX API metadata/connection exports, CC Switch Claude provider JSON (`settingsConfig.env`), and Magpie `providers.json` with native API bases. Cached deployment evidence, foreign route aliases, account rotation, commands and tool permissions are not adopted. Credential values are not copied; use a private key input or `key_env` when saving. Client access remains a separate explicit choice.
165
181
 
182
+ Choose **CC Switch** or **Magpie** under Import to find their local API configuration. The CLI/TUI equivalent is `source import --from cc-switch` or `--from magpie`; do not combine `--from` with `--file`. This works without starting a gateway. Applying one reviewed draft still uses `--select N --apply --key-stdin --yes` and requires the running service. Foreign keys and permissions are never copied.
183
+
184
+ CC Switch discovery uses its `app_paths.json` directory override when present, then its default `~/.cc-switch/cc-switch.db` (including the known Windows legacy-home fallback). It reads Claude Code/Desktop API declarations and explicitly declared Codex Chat/Responses providers. OAuth-only, Gemini-native, ambiguous and invalid configurations are skipped. Magpie reads `providers.json` under an absolute `XDG_CONFIG_HOME/magpie`, or `~/.config/magpie`; portable/custom exports can use the existing file import. Only native API bases are adopted; local proxy addresses remain subject to the existing HTTPS validation.
185
+
186
+ Discovery runs only after an explicit action, in a short separate process. It does not scan the disk, execute foreign commands, copy credential databases, refresh model catalogs or change the other tool. Missing, busy, damaged and unknown stores keep file import available. A live SQLite WAL is read through the normal read-only connection; an orphaned WAL is left for its owning tool to recover. Reads examine at most 64 candidate records and show up to 16 valid drafts. Same-name and same-address warnings require review; matching addresses never imply matching accounts. Select **Review draft**, enter the key privately and save before granting client access or selecting models.
187
+
166
188
  The preview reports existing source names/addresses and fields requiring review. **Review draft** opens the existing API editor. The CLI can save one reviewed draft with `--select N --apply --key-stdin --yes`; this grants no app access. Unsupported shapes and mixed-origin endpoints fail validation without writes.
167
189
 
168
190
  Model details can declare `max_tool_definitions` and `supported_parameters`. Catalog parameter lists apply only to their explicitly named protocol. Source input, output and context limits remain separate. Known unsupported parameters, invalid positive-integer output limits and excessive tool definitions fail before dispatch. Unknown metadata remains unknown; CCDX does not guess limits from a model name or remove requested tools.
@@ -234,6 +256,16 @@ ccdx requests --app antigravity --active
234
256
 
235
257
  For an identified conversation, hovering a point in the input-history chart shows that request's available cache-reuse ratio. Missing or invalid counts remain unknown; the bounded in-memory history and retained usage do not change.
236
258
 
259
+ ## Shared source concurrency
260
+
261
+ All three Apps share admission for the same configured source and account. A slot spans the real upstream response body through completion, cancellation or error. Request-body memory is tracked separately; unknown-length uploads retain their full reservation until fully read, then shrink to their actual held bytes. Recovery and internal summaries acquire fresh slots after the rejected response releases its slot.
262
+
263
+ Automatic control distinguishes explicit concurrency rejection, request-rate feedback and quota exhaustion. Clear concurrency feedback lowers capacity without interrupting active streams; stable successful traffic with real waiting demand slowly increases it. Explicit account-wide rate/quota evidence pauses that account; model-scoped feedback leaves sibling models available after a short spacing interval. Unknown 429s use bounded backoff. Parameters, permissions and long thinking time do not train concurrency. There are no quota probes or automatic source/account/model switches. A first upstream limit rejection can still occur before its capacity is known.
264
+
265
+ The initial internal ceiling is 128 concurrent requests per source/account. This is a local resource bound, not an upstream allowance. Each account queues at most 16 calls; all source queues together retain at most 8 MiB and wait at most 30 seconds. Runnable client queues rotate while preserving each client's order among runnable calls. Longer reported recovery times return a local 429 with Retry-After; a full or expired queue returns an explicit busy/wait error. Existing active streams are never cancelled to enforce a lower ceiling. Ordinary generation retry behavior remains unchanged.
266
+
267
+ **Model sources → Concurrency** normally stays **Auto**. Leave the optional maximum blank, or set 1–128 as a ceiling. CLI/TUI use `source <id> limits`, `--edit`, or `--max auto|N`. This does not disable automatic adjustment. Stable account capacity is saved as disposable hashed metadata beside service settings, with no request text, keys or raw account IDs; stale or invalid metadata is ignored.
268
+
237
269
  ## Settings and appearance
238
270
 
239
271
  Settings separates saved preferences from effective state. Auto-save applies changes by default; required restarts remain explicit. Restore-defaults creates a backup first and keeps accounts, keys, model plans and chats. CLI preference reset/restore uses its own service-only backup; it does not change browser appearance or replace the Web UI's backup.
@@ -607,7 +639,7 @@ rolls back newly added trust; certificate replacement keeps old trust until the
607
639
  new preference is committed. If the bridge stops, new connections can fall back
608
640
  to the original route; already-interrupted requests are not replayed. An App
609
641
  already using the saved address need not be relaunched just because CCDX restarts.
610
- If its route is missing or differs, fully quit Codex and run `ccdx` to attach it.
642
+ If its route is missing or differs, fully quit Codex and open it from its CCDX page.
611
643
  `CCDX_AUTO_LAUNCH=0` keeps automatic launch disabled and never hot-attaches a
612
644
  running App. An already-persisted direct-environment preference can still be read
613
645
  when the App is manually opened.
@@ -677,7 +709,7 @@ to gain this endpoint; the new CLI cannot hot-upgrade an old Node process.
677
709
  Repair reports bridge readiness separately from the inspected App launch route.
678
710
  If a running App has no verified route, fix returns a partial result (exit 1), preserves
679
711
  its process and asks for a normal full quit followed by `ccdx`. A closed App is not
680
- launched by fix; run `ccdx` to open it. Neither HTTP 200 nor a verified route proves
712
+ launched by fix; use the Codex page to open it. Neither HTTP 200 nor a verified route proves
681
713
  that gray text appeared. Normal replies, image setup and account state are not changed.
682
714
  Unavailable/ambiguous process inspection reports `route_unverified` (exit 1), not
683
715
  a definite missing route or an instruction to restart an otherwise healthy App.
@@ -802,7 +834,7 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
802
834
  | `CCDX_IMG_MAX_INPUT_PIXELS` | `40000000` | Sharp's per-image decode limit; an optimization failure retains the original image, subject to the overall forwarded-body limit |
803
835
  | `CCDX_IMG_CACHE_MAX_BYTES` | `67108864` | Process-local byte ceiling for cached image transforms; set to `0` to disable the cache |
804
836
  | `CCDX_DISABLE_IMG_OPT` | unset | Set to `1` to disable image optimization |
805
- | `CCDX_AUTO_LAUNCH` | enabled | Set to `0`, `false`, `no`, or `off` to start without opening Codex App |
837
+ | `CCDX_AUTO_LAUNCH` | saved preference, off | Explicitly override automatic Codex opening; `1` enables, `0`, `false`, `no`, or `off` disables |
806
838
  | `CCDX_GITHUB_TOKEN` | unset | Explicit GitHub Copilot OAuth token to validate and import before Device Flow |
807
839
  | `CCDX_GITHUB_TOKEN_PATH` | unset | Explicit file containing a GitHub Copilot OAuth token |
808
840
  | `CCDX_GITHUB_TOKEN_PATHS` | unset | Multiple token files separated by the platform path delimiter (`:` on macOS, `;` on Windows) |
@@ -820,6 +852,8 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
820
852
  | `CCDX_DISABLE_USAGE` | unset | Set to `1` to disable usage logging |
821
853
  | `CCDX_SHUTDOWN_TIMEOUT_MS` | `5000` | Time to drain active HTTP connections before forcing shutdown |
822
854
 
855
+ Antigravity starts the body deadline after queue admission. Its generation requests release body reservations after the final upstream response opens, while keeping response-restoration state until completion. Queue exhaustion or timeout returns `503`; a body timeout returns `408`; upstream and compaction timeouts return `504`. Client cancellation releases queued or active reservations. These limits and queue ordering remain unchanged.
856
+
823
857
  ## Usage logging
824
858
 
825
859
  When upstream responses contain usage fields, CCDX records token counts, model names, API surface, and response IDs in `~/.local/share/codex-copilot-dx/usage.jsonl`. It does not record prompts, completions, tool arguments, or image content.
@@ -933,7 +967,7 @@ MIT
933
967
  | --- | --- |
934
968
  | `ADAPTER_HOST` | Listener host; default loopback |
935
969
  | `ADAPTER_PORT` | Main listener port; default 2026 |
936
- | `CCDX_AUTO_LAUNCH` | Set to 0 to skip opening Codex |
970
+ | `CCDX_AUTO_LAUNCH` | Override saved automatic Codex opening; default off |
937
971
  | `CCDX_M365` | Set to 0 to disable the company source for this run |
938
972
  | `CCDX_USAGE_PATH` | Recorded usage file path |
939
973
  | `CCDX_LOG_LEVEL` | Optional diagnostic logging level |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.4.3",
3
+ "version": "1.4.5",
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",
@@ -117,13 +117,15 @@ export function defaultAccessSettings() {
117
117
  { enabled: true, allowed: id === "codex" ? ["github", "m365"] : ["m365"], source: null }])) };
118
118
  }
119
119
  export function checkedAccessSettings(value) {
120
- if (!fields(value, ["version", "claude_private_keys", "providers", "apis", "clients"]) || ![1, 2].includes(value.version) || typeof value.claude_private_keys !== "boolean"
120
+ if (!fields(value, ["version", "claude_private_keys", "providers", "apis", "clients", "source_limits"]) || ![1, 2].includes(value.version) || typeof value.claude_private_keys !== "boolean"
121
121
  || !fields(value.providers, ["github", "m365"]) || ["github", "m365"].some(id => typeof value.providers[id] !== "boolean")
122
122
  || !Array.isArray(value.apis) || value.apis.length > 16 || !fields(value.clients, CLIENT_IDS)) throw accessError("ccdx_connections_invalid");
123
123
  const ids = new Set(["github", "m365"]), names = new Set(["github copilot", "microsoft 365"]);
124
124
  for (const api of value.apis) { checkedApi(api);if (ids.has(api.id)) throw accessError("ccdx_connections_invalid");ids.add(api.id);
125
125
  const name = api.name.trim().toLowerCase();if (names.has(name)) throw accessError("ccdx_api_name_exists");names.add(name);
126
126
  }
127
+ if (value.source_limits !== undefined && (!fields(value.source_limits, [...ids]) || Object.values(value.source_limits).some(limit => !Number.isSafeInteger(limit) || limit < 1 || limit > 128)))
128
+ throw accessError("ccdx_connections_invalid");
127
129
  for (const id of CLIENT_IDS) {
128
130
  const client = value.clients[id];
129
131
  if (!fields(client, ["enabled", "allowed", "source", "model", "auto_review_model", "auto_review_effort", "history_isolation", "deployments", "default_model", "auto_sync", "image_model"])
@@ -134,7 +136,8 @@ export function checkedAccessSettings(value) {
134
136
  || client.auto_sync !== undefined && typeof client.auto_sync !== "boolean"
135
137
  || client.default_model !== undefined && client.default_model !== null && !modelId(client.default_model)
136
138
  || client.deployments !== undefined && client.deployments !== null && (!Array.isArray(client.deployments) || client.deployments.length > 1000
137
- || client.deployments.some(item => !fields(item, ["source", "model"]) || !client.allowed.includes(item.source) || !modelId(item.model))
139
+ || client.deployments.some(item => !fields(item, ["source", "model", "reasoning_effort"]) || !client.allowed.includes(item.source) || !modelId(item.model)
140
+ || item.reasoning_effort !== undefined && (id !== "claude_app" || !["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(item.reasoning_effort)))
138
141
  || new Set(client.deployments.map(item => item.source + "\0" + item.model)).size !== client.deployments.length)
139
142
  || client.history_isolation !== undefined && typeof client.history_isolation !== "boolean"
140
143
  || client.auto_review_effort !== undefined && client.auto_review_effort !== null && !["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(client.auto_review_effort)) throw accessError("ccdx_connections_invalid");
package/src/adapter.mjs CHANGED
@@ -159,7 +159,7 @@ async function sendLastKnownGoodModels(res, modelRegistry, options = {}) {
159
159
  // Shared request handler. Keeping this separate from the listener makes the
160
160
  // complete HTTP routing layer testable without opening a local port.
161
161
  export function createAdapterHandler(options = {}) {
162
- const codexClient = options.codexClient || defaultCopilotClient;
162
+ const codexClient = options.codexClient || options.providerRuntime?.source?.("github")?.client || defaultCopilotClient;
163
163
  // Keep the established injection names because Responses may still use the
164
164
  // internal Chat Completions compatibility path for upstream models that need it.
165
165
  const chatCompletionsFn = options.codexChatCompletionsFn
@@ -193,6 +193,9 @@ export function createAdapterHandler(options = {}) {
193
193
  if (!antigravityLoading) antigravityLoading = (async () => {
194
194
  const { createAntigravityRuntime } = await import("./antigravity-runtime.mjs");
195
195
  antigravity = createAntigravityRuntime({ client: codexClient, models: () => codexModelRegistry?.models || [], privacy, compaction, acquireRequest,
196
+ applicationControl: options.dashboardOptions?.serviceControl?.applicationControl,
197
+ sourceAdmission: options.providerRuntime?.sourceAdmission,
198
+ applicationEvidence: options.providerRuntime?.applicationEvidence,
196
199
  ...(options.providerRuntime?.dashboardCatalog?{refreshModels:async()=>{
197
200
  const result=await options.providerRuntime.dashboardCatalog({provider:"github"});
198
201
  if(!result)throw httpError("GitHub model catalog refresh is unavailable",503);
@@ -507,6 +510,9 @@ export function createAdapterHandler(options = {}) {
507
510
  if (typeof finish === "function") finishTerminalActivity = finish;
508
511
  } catch {}
509
512
  }
513
+ const applicationEvidenceScope = req.method === "GET" && pathname === "/v1/models" ? "catalog"
514
+ : req.method === "POST" && (pathname === "/v1/responses" || pathname === "/v1/responses/compact") ? "inference" : null;
515
+ const applicationEvidenceAt = applicationEvidenceScope ? Date.now() : 0;
510
516
  let requestFinished = false;
511
517
  let httpEvidence = {}, context;
512
518
  const finishRequest = ({ statusCode = 0, aborted = false } = {}) => {
@@ -527,6 +533,8 @@ export function createAdapterHandler(options = {}) {
527
533
  rejectionReason: httpEvidence.reason || (httpEvidence.code === "ccdx_client_source_disabled" ? httpEvidence.code : undefined) }); } catch {}
528
534
  try { finishTerminalActivity(); } catch {}
529
535
  try { context?.finishProvider?.(); } catch {}
536
+ if (applicationEvidenceScope && !aborted && statusCode >= 200 && statusCode < 300)
537
+ options.providerRuntime?.applicationEvidence?.accept(req, "codex", applicationEvidenceScope, applicationEvidenceAt);
530
538
  };
531
539
  const containUnexpectedError = (error) => {
532
540
  try { finishRequest({ statusCode: res.statusCode >= 400 ? res.statusCode : 500 }); } catch {}
@@ -2,6 +2,8 @@ import { createHash } from "node:crypto";
2
2
  import { webStreamLines } from "./stream.mjs";
3
3
  import { MAX_UPSTREAM_CHAT_SUCCESS_BODY_BYTES } from "./http-transport.mjs";
4
4
  import { ToolArgumentDeltaGuard, upstreamChatStreamError } from "./stream-contract.mjs";
5
+ import { observeSourceStreamFailure } from "./source-admission.mjs";
6
+ import { sourceResponseAccepted } from "./source-response.mjs";
5
7
 
6
8
  const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
7
9
  const names = /^[A-Za-z0-9_-]{1,64}$/;
@@ -187,12 +189,12 @@ export async function* chatStreamToAntigravity(response, originalNames, { onChun
187
189
  const raw = data.join("\n");data.length = 0;
188
190
  if (raw === "[DONE]") { done = true;return; }
189
191
  let event;try { event = JSON.parse(raw); } catch { throw invalid("Invalid upstream Chat stream event", 502); }
190
- const upstreamError = upstreamChatStreamError(event);if (upstreamError) throw upstreamError;
192
+ const upstreamError = upstreamChatStreamError(event);if (upstreamError) { observeSourceStreamFailure(response, event.error);throw upstreamError; }
191
193
  if (event?.usage) usage = event.usage;
192
194
  if (event?.usage || event?.copilot_usage) onUsage?.(event);
193
195
  const choice = event?.choices?.[0];
194
196
  if (!choice) return;
195
- if (choice.finish_reason) finish = choice.finish_reason;
197
+ if (choice.finish_reason) { finish = choice.finish_reason;sourceResponseAccepted(response); }
196
198
  const delta = choice.delta || {};
197
199
  for (const [key, thought] of [["reasoning_content", true], ["content", false], ["refusal", false]]) {
198
200
  if (delta[key] === undefined || delta[key] === null || delta[key] === "") continue;
@@ -1,6 +1,6 @@
1
1
  import {randomUUID,createHash} from "node:crypto";
2
2
  import {buildResponsesUsageRecord,recordUsage} from "./usage-store.mjs";
3
- import {createRequestAbort,readJsonBody,readBoundedResponseText,writeOrDrain,httpError,sendJsonError} from "./http-transport.mjs";
3
+ import {createRequestAbort,abortErrorStatusCode,readJsonBody,readBoundedResponseText,writeOrDrain,httpError,sendJsonError} from "./http-transport.mjs";
4
4
  import {safeUpstreamResponseHeaders} from "./upstream-headers.mjs";
5
5
  import {isLoopbackAddress,isLoopbackHostHeader} from "./security.mjs";
6
6
  import {antigravityToChat,chatToAntigravity,chatStreamToAntigravity,parseAntigravityJSON} from "./antigravity-chat-bridge.mjs";
@@ -8,11 +8,12 @@ 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,markToolActivity} from "./stream-performance.mjs";
11
+ import {measureRequestStageAsync,markUpstreamStarted,markUpstreamHeaders,markFirstOutput,markOutputTokens,markRequestObservation,markResponseModel,markResponseErrorOrigin,markResponseTerminal,markToolActivity} from "./stream-performance.mjs";
12
12
  import {isCompactionRequest} from "./context-compaction.mjs";
13
13
  import {compactionSummarizer} from "./context-compaction-wire.mjs";
14
14
  import {requestPurpose} from "./request-context.mjs";
15
15
  import {observeContextSession} from "./context-metrics.mjs";
16
+ import {sourceResponseReader,observeSourceRead,failSourceRead,cancelSourceReader,releaseSourceReader,cancelSourceResponse,sourceResponseAccepted,sourceResponseFailed} from "./source-response.mjs";
16
17
 
17
18
  const PREFIX="/antigravity";
18
19
  const MAX_REPLY=64*1024*1024;
@@ -36,13 +37,17 @@ function groundedSearch(result,query){
36
37
  groundingMetadata:{webSearchQueries:[query],groundingChunks:sources.map(item=>({web:{uri:item.url,title:item.title||item.url}}))}}]};
37
38
  }
38
39
 
39
- export function createAntigravityHandler({client,models=()=>[],selectedModels=()=>null,enabled=()=>false,privacy,searchFn,imageFn,guardSource,acquireRequest=async()=>()=>{},
40
+ export function createAntigravityHandler({client,models=()=>[],selectedModels=()=>null,enabled=()=>false,privacy,searchFn,imageFn,guardSource,acquireRequest=async()=>()=>{},sourceAdmission,applicationEvidence,
40
41
  compaction,compactionProfile=()=>"github",rememberConversationSource=()=>{},resolveCompactionSource=()=>null,recordUsageFn=recordUsage,fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,streamIdleTimeoutMs=60000}={}) {
41
42
  if(![GOOGLE_ORIGIN,"https://cloudcode-pa.googleapis.com"].includes(googleOrigin))throw new Error("Unrecognized Google control origin");
42
43
  let active=0,observed=false,catalogModels=null;const nativeWindows=new Map();
43
44
  const counts={total:0,google:0,copilot:0,search:0,images:0,failed:0};
44
45
  const handler=async(req,res)=>{
45
- const abort=createRequestAbort(req,res);let release=()=>{},session,usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
46
+ const abort=createRequestAbort(req,res);let release=()=>{},session,body,request,converted,phase="validation",usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
47
+ const releaseInput=()=>{
48
+ body=null;request=null;if(converted)converted.chat=null;if(session)session.body=null;
49
+ const done=release;release=()=>{};done();
50
+ };
46
51
  const captureUsage=event=>{
47
52
  if(!event?.usage&&!event?.copilot_usage)return;
48
53
  const known=value=>Number.isSafeInteger(value)&&value>=0,u={...usageEvent?.usage},incoming=event.usage;
@@ -66,9 +71,12 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
66
71
  const match=/^\/v1internal(?::|\/)([A-Za-z][A-Za-z0-9]*)$/.exec(route);
67
72
  if(!local.pathname.startsWith(PREFIX+"/")||!match)throw httpError("Unknown Antigravity endpoint",404);
68
73
  const method=match[1];
69
- abort.setTimeout(requestBodyTimeoutMs,"request_body_timeout");release=await acquireRequest(req,{signal:abort.signal});
74
+ if(controlMethods.has(method))applicationEvidence?.notice(req,res,"antigravity","control");
70
75
  if(req.method==="POST"&&!/^application\/json(?:;|$)/i.test(req.headers["content-type"]||""))throw httpError("Antigravity requires JSON",415);
71
- let body=req.method==="POST"?await readJsonBody(req,{admission:release,signal:abort.signal,parse:parseBody}):null;
76
+ phase="admission";release=await measureRequestStageAsync("admission",()=>acquireRequest(req,{signal:abort.signal}));
77
+ phase="body";abort.setTimeout(requestBodyTimeoutMs,"request_body_timeout");
78
+ body=req.method==="POST"?await measureRequestStageAsync("body",()=>readJsonBody(req,{admission:release,signal:abort.signal,parse:parseBody})):null;
79
+ phase="preparation";
72
80
  const context=currentRequestContext();if(context)context.application="gemini_app";
73
81
  const compacting=isCompactionRequest("gemini",body);
74
82
  if(compacting&&context){context.purpose=requestPurpose(req.headers["x-ccdx-purpose"],"compaction");context.streamPerformance?.setPurpose(context.purpose)}
@@ -90,14 +98,22 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
90
98
  }
91
99
  const open=async(value,options={})=>{
92
100
  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;
101
+ const serialized=value?JSON.stringify(value):undefined,signal=options.signal||abort.signal;
102
+ const perform=()=>{
103
+ if(generation){abort.setTimeout(upstreamTimeoutMs,"upstream_timeout");markUpstreamStarted(internal||method==="streamGenerateContent")}
104
+ return fetchGoogle(googleOrigin+path,{method:internal?"POST":req.method,headers:{...nativeHeaders(req),...(value?{"content-type":"application/json"}:{}),...(internal?{accept:"text/event-stream"}:{})},
105
+ ...(serialized?{body:serialized}:{}),signal,redirect:"error"});
106
+ };
107
+ const result=generation&&sourceAdmission?await sourceAdmission.run({source:"google",account:createHash("sha256").update(req.headers.authorization||"").digest("hex")},perform,
108
+ {signal,sourceBodyManaged:true,model:value?.model,client:"gemini_app",bytes:()=>Buffer.byteLength(serialized||"")}):await perform();
109
+ if(generation){markUpstreamHeaders(result.status);applicationEvidence?.accept(req,"antigravity","inference")}return result;
97
110
  };
111
+ phase="upstream";
98
112
  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
113
  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
114
  summarize:compactionSummarizer(body,"gemini",(value,options)=>open(value,{...options,internal:true})),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await open(body);
115
+ releaseInput();
116
+ if(!upstream.ok)markResponseErrorOrigin("upstream_http");
101
117
  if(method==="fetchAvailableModels"&&upstream.ok){
102
118
  const value=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:8*1024*1024,signal:abort.signal,label:"Google model catalog"}));
103
119
  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)}
@@ -112,20 +128,22 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
112
128
  const response=value?.response||value,event=googleUsageEvent(value);if(event)captureUsage(event);
113
129
  const candidates=response?.candidates||[];
114
130
  if(candidates.some(candidate=>candidate.content?.parts?.some(part=>part.functionCall||!part.thought&&typeof part.text==="string"&&part.text)))markFirstOutput("delta");
115
- if(response?.error)outcome="failed";
131
+ if(response?.error){outcome="failed";sourceResponseFailed(upstream)}
116
132
  else if(outcome!=="failed"&&candidates.some(candidate=>candidate.finishReason)){
133
+ sourceResponseAccepted(upstream);
117
134
  outcome=candidates.every(candidate=>candidate.finishReason==="STOP")?"completed":"incomplete";
118
135
  }
119
136
  }}):null;
120
137
  res.writeHead(upstream.status,safeUpstreamResponseHeaders(upstream.headers));
121
138
  try{
122
- if(upstream.body)for await(const data of upstream.body){
123
- abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout");observer?.push(data);
124
- if(!await writeOrDrain(res,data,{signal:abort.signal}))throw httpError("Antigravity client disconnected",499);
125
- }
139
+ if(upstream.body){const reader=sourceResponseReader(upstream);try{while(true){
140
+ let next;try{next=await reader.read()}catch(error){failSourceRead(reader);throw error}observeSourceRead(reader,next);if(next.done)break;
141
+ abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout");observer?.push(next.value);
142
+ if(!await writeOrDrain(res,next.value,{signal:abort.signal}))throw httpError("Antigravity client disconnected",499);
143
+ }}finally{await cancelSourceReader(reader).catch(()=>{});releaseSourceReader(reader)}}
126
144
  }finally{if(observer?.finish().unavailable&&!usageEvent)markRequestObservation({usage_state:"unavailable"})}
127
145
  if(generation&&!upstream.ok)outcome="failed";
128
- if(outcome)markResponseTerminal(outcome);
146
+ if(outcome)markResponseTerminal(outcome,upstream.ok?undefined:{origin:"upstream_http"});
129
147
  res.end();
130
148
  };
131
149
  if(!generation){
@@ -148,13 +166,13 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
148
166
  if(context){context.provider="github";context.streamPerformance?.setProvider?.("github")}
149
167
  observeContextSession(null,{session_id:body.request?.labels?.root_cascade_id||body.request?.labels?.cascade_id},{profileId:()=>"github:codex"},"chat");
150
168
  context?.streamPerformance?.observeToolInput?.(body.request,"gemini");
151
- const request=body.request;
169
+ request=body.request;
152
170
  if(body.requestType==="web_search"){
153
171
  counts.search++;if(!searchFn)throw httpError("Copilot search is unavailable",503);
154
172
  const query=searchQuery(request),input={id:randomUUID(),commands:{search_query:[{q:query}]}};
155
173
  session=privacy?.prepareSession?await privacy.prepareSession(input,{protocol:"search",client:"gemini",signal:abort.signal}):passthrough(input);
156
174
  const response=await searchFn(session.body,{signal:abort.signal});
157
- if(!response.ok)throw httpError("Copilot search was refused (HTTP "+response.status+")",response.status);
175
+ if(!response.ok){await cancelSourceResponse(response).catch(()=>{});throw httpError("Copilot search was refused (HTTP "+response.status+")",response.status)}
158
176
  const result=session.restoreValue(JSON.parse(await readBoundedResponseText(response,{maxBytes:8*1024*1024,signal:abort.signal,label:"Copilot search"})));
159
177
  markResponseTerminal("completed");
160
178
  res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response:groundedSearch(result,query)}));return;
@@ -169,15 +187,18 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
169
187
  const target=body.requestType==="agent"||compactBinding&&!compactBinding.background?selected:copilotModels.find(model=>model.model==="gemini-4-carbon"&&model.effort==="low");
170
188
  if(!target)throw httpError("Copilot Carbon is unavailable for Antigravity background tasks",503);
171
189
  const stream=method==="streamGenerateContent";usageModel=target.model;usageMode=stream?"sse":"json";usageProvider="github";
172
- const converted=antigravityToChat(request,{model:target.model,effort:target.effort,reasoningEfforts:target.effort?[target.effort]:[],stream});
190
+ converted=antigravityToChat(request,{model:target.model,effort:target.effort,reasoningEfforts:target.effort?[target.effort]:[],stream});
173
191
  markResponseModel(target.model);markRequestObservation({usage_state:"pending"});
174
192
  session=privacy?.prepareSession?await privacy.prepareSession(converted.chat,{protocol:"chat",client:"gemini",signal:abort.signal}):passthrough(converted.chat);
175
- const callOptions={signal:abort.signal,retryOptions:{retries:0},onUpstreamStart:()=>abort.setTimeout(upstreamTimeoutMs,"upstream_timeout")};
193
+ const callOptions={signal:abort.signal,sourceBodyManaged:true,retryOptions:{retries:0},onUpstreamStart:()=>abort.setTimeout(upstreamTimeoutMs,"upstream_timeout")};
194
+ phase="upstream";
176
195
  const upstream=compacting&&compaction?await compaction.run({body:session.body,protocol:"chat",scope:JSON.stringify(["gemini","github",compactionProfile()]),source:"github",client:"gemini",
177
196
  inputLimit:target.maxTokens,outputAllowance:session.body.max_completion_tokens||session.body.max_tokens||0,native:client.chatCompletions,options:callOptions,
178
197
  summarize:compactionSummarizer(session.body,"chat",client.chatCompletions),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await client.chatCompletions(session.body,callOptions);
198
+ releaseInput();
179
199
  markUpstreamHeaders(upstream.status);
180
- if(!upstream.ok){await upstream.body?.cancel();throw httpError("Copilot generation was refused (HTTP "+upstream.status+")",upstream.status)}
200
+ applicationEvidence?.accept(req,"antigravity","inference");
201
+ if(!upstream.ok){markResponseErrorOrigin("upstream_http");await cancelSourceResponse(upstream).catch(()=>{});throw httpError("Copilot generation was refused (HTTP "+upstream.status+")",upstream.status)}
181
202
  if(!stream){
182
203
  const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));captureUsage(data);
183
204
  const result=chatToAntigravity(data,converted.originalNames);markToolActivity(result,"gemini");
@@ -200,13 +221,19 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
200
221
  }
201
222
  res.end();
202
223
  }catch(error){
224
+ if(abort.reason)error=Object.assign(httpError(error.message,abortErrorStatusCode(abort.reason)),{code:abort.reason});
225
+ else if(phase==="admission")error=Object.assign(httpError(error.message,error.statusCode||503),{code:"ccdx_request_admission_unavailable"});
203
226
  if(typeof error.code==="string"&&error.code.startsWith("ccdx_compaction_"))res.setHeader("x-should-retry","false");
204
227
  counts.failed++;
205
- outcome=abort.signal.aborted&&["client_closed","client_aborted"].includes(abort.reason)?"cancelled":"failed";markResponseTerminal(outcome);
228
+ const cancelled=abort.signal.aborted&&["client_closed","client_aborted"].includes(abort.reason);
229
+ if(cancelled)markRequestObservation({delivery_cancelled:1});
230
+ if(!cancelled||!["completed","incomplete"].includes(outcome))outcome=cancelled?"cancelled":"failed";
231
+ const origin=outcome==="cancelled"?"client_disconnect":currentRequestContext()?.errorOrigin||(abort.reason||phase==="admission"?"transport":["privacy","source_admission"].includes(error.origin)?error.origin:error.statusCode<500?"client_validation":"transport");
232
+ markResponseErrorOrigin(origin);markResponseTerminal(outcome,{origin});
206
233
  if(res.headersSent&&!res.writableEnded&&!res.destroyed){res.end("data: "+JSON.stringify({error:{code:error.statusCode||502,message:error.message}})+"\n\n");}
207
234
  else sendJsonError(res,error,error.statusCode||502);
208
235
  }finally{
209
- session?.release();release();abort.cleanup();active--;
236
+ releaseInput();session?.release();abort.cleanup();active--;
210
237
  if(usageEvent){
211
238
  const u=usageEvent.usage,record=buildResponsesUsageRecord({surface:"antigravity",mode:usageMode,model:usageModel,
212
239
  response:{id:usageEvent.id,model:usageEvent.model||usageModel,usage:u?{input_tokens:u.prompt_tokens,output_tokens:u.completion_tokens,
@@ -216,7 +243,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
216
243
  markRequestObservation({input_tokens:record.usage?.input_tokens,cached_input_tokens:record.usage?.cached_input_tokens});
217
244
  const context=currentRequestContext();
218
245
  recordUsageFn({...record,provider:usageProvider,client:"gemini",request_id:context?.requestId,requested_model:context?.requestedModel,
219
- outcome:outcome||"unknown",...(outcome!=="completed"?{partial:true}:{})});
246
+ outcome:outcome||"unknown",...(outcome!=="completed"||abort.signal.aborted?{partial:true}:{})});
220
247
  }
221
248
  }
222
249
  }
@@ -1,6 +1,7 @@
1
1
  import {nativeImageRequest,checkedImage,IMAGE_MAX_BYTES} from "./native-images.mjs";
2
2
  import {imageModelCatalog,imageModelSelection} from "./image-models.mjs";
3
3
  import {httpError,readBoundedResponseText} from "./http-transport.mjs";
4
+ import {cancelSourceResponse} from "./source-response.mjs";
4
5
 
5
6
  export function createAntigravityImages({client,models,privacy}={}) {
6
7
  return async(request,{signal}={})=>{
@@ -17,8 +18,8 @@ export function createAntigravityImages({client,models,privacy}={}) {
17
18
  const body=await nativeImageRequest({model:selected,prompt:text.join("\n"),...(images.length?{images}:{}),n:1},operation,selected);
18
19
  const session=privacy?.prepareSession?await privacy.prepareSession({input:body.prompt},{protocol:"responses",client:"gemini",signal}):null;
19
20
  try{
20
- const response=await client.images(operation,{...body,prompt:session?.body.input||body.prompt},{signal});
21
- if(!response.ok){await response.body?.cancel();throw httpError("Copilot image generation was refused (HTTP "+response.status+")",response.status)}
21
+ const response=await client.images(operation,{...body,prompt:session?.body.input||body.prompt},{signal,sourceBodyManaged:true});
22
+ if(!response.ok){await cancelSourceResponse(response).catch(()=>{});throw httpError("Copilot image generation was refused (HTTP "+response.status+")",response.status)}
22
23
  const value=JSON.parse(await readBoundedResponseText(response,{maxBytes:48*1024*1024,signal,label:"Copilot image"}));
23
24
  if(!Array.isArray(value.data)||value.data.length!==1)throw httpError("Invalid Copilot image response",502);
24
25
  const data=value.data[0].b64_json,mimeType=await checkedImage(data,IMAGE_MAX_BYTES);