codex-copilot-dx 1.4.4 → 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 (64) hide show
  1. package/README.md +2 -1
  2. package/bin/cli.mjs +5 -4
  3. package/docs/ARCHITECTURE.md +16 -0
  4. package/docs/REFERENCE.md +34 -8
  5. package/package.json +1 -1
  6. package/src/access-settings.mjs +3 -1
  7. package/src/adapter.mjs +9 -1
  8. package/src/antigravity-chat-bridge.mjs +4 -2
  9. package/src/antigravity-handler.mjs +28 -16
  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 +24 -15
  17. package/src/cli-command-spec.mjs +7 -4
  18. package/src/cli-management.mjs +27 -2
  19. package/src/codex-image-host-launch.mjs +1 -2
  20. package/src/codex-launch-control.mjs +7 -7
  21. package/src/connection-management.mjs +18 -3
  22. package/src/connection-policy.mjs +3 -1
  23. package/src/connection-routing.mjs +7 -2
  24. package/src/connection-runtime.mjs +21 -5
  25. package/src/connection-view.mjs +9 -3
  26. package/src/context-compaction-wire.mjs +7 -6
  27. package/src/context-compaction.mjs +6 -4
  28. package/src/copilot-client.mjs +17 -13
  29. package/src/copilot-responses-compat.mjs +1 -0
  30. package/src/copilot-web.mjs +6 -2
  31. package/src/dashboard/applications.js +83 -0
  32. package/src/dashboard/connections.js +52 -14
  33. package/src/dashboard/console.js +19 -9
  34. package/src/dashboard/gemini.js +8 -5
  35. package/src/dashboard/index.html +16 -0
  36. package/src/dashboard/language.js +41 -0
  37. package/src/dashboard/ui.css +9 -0
  38. package/src/dashboard-api.mjs +6 -1
  39. package/src/dashboard.mjs +1 -0
  40. package/src/gemini-app.mjs +3 -2
  41. package/src/http-transport.mjs +5 -2
  42. package/src/launcher.mjs +6 -5
  43. package/src/native-images.mjs +1 -1
  44. package/src/provider-runtime.mjs +14 -9
  45. package/src/providers/api.mjs +18 -12
  46. package/src/providers/m365.mjs +9 -5
  47. package/src/request-admission.mjs +6 -0
  48. package/src/responses-bridge.mjs +5 -2
  49. package/src/responses-handler.mjs +2 -0
  50. package/src/responses-proxy.mjs +9 -4
  51. package/src/safe-upstream-error.mjs +9 -11
  52. package/src/service-control.mjs +29 -5
  53. package/src/settings-preferences.mjs +3 -3
  54. package/src/source-admission-state.mjs +29 -0
  55. package/src/source-admission.mjs +310 -0
  56. package/src/source-discovery-probe.mjs +35 -0
  57. package/src/source-discovery.mjs +112 -0
  58. package/src/source-response.mjs +134 -0
  59. package/src/source-transport.mjs +19 -0
  60. package/src/stream-contract.mjs +3 -1
  61. package/src/stream-performance.mjs +3 -1
  62. package/src/stream.mjs +6 -4
  63. package/src/upstream-body.mjs +9 -8
  64. package/src/user-settings.mjs +2 -2
package/README.md CHANGED
@@ -51,6 +51,7 @@ Model availability depends on your account and service. Microsoft 365 also requi
51
51
  | Open the Web UI | `ccdx web` |
52
52
  | Check service and apps | `ccdx status` / `ccdx app list` |
53
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` |
54
55
  | Manage sources | `ccdx source list` / `ccdx source add` |
55
56
  | Sign in again | `ccdx source github reauth` |
56
57
  | Choose client models | `ccdx app codex models --edit` |
@@ -72,7 +73,7 @@ Use `ccdx help` or `ccdx <command> --help` for options. The CLI uses English; th
72
73
 
73
74
  ## Features and maintenance
74
75
 
75
- 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.
76
77
 
77
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).
78
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
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,6 +54,12 @@ 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.
@@ -92,10 +102,10 @@ error rather than successful completion.
92
102
 
93
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.
94
104
 
95
- `enable` saves CCDX settings and prepares its local source guard. `open --preview` shows the launch plan.
96
- `open` starts a closed, signed `/Applications/Gemini.app` with a process-local
97
- Antigravity endpoint. An already running App is kept open and must be quit by
98
- 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
99
109
  conflict instead of being overwritten. The Gemini bundle, Google credentials,
100
110
  global proxy and certificates are untouched. Endpoint adoption remains
101
111
  unconfirmed until an Antigravity request is observed.
@@ -169,6 +179,12 @@ A saved fallback is applied as Messages `output_config.effort` only when the App
169
179
 
170
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.
171
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
+
172
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.
173
189
 
174
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.
@@ -240,6 +256,16 @@ ccdx requests --app antigravity --active
240
256
 
241
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.
242
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
+
243
269
  ## Settings and appearance
244
270
 
245
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.
@@ -613,7 +639,7 @@ rolls back newly added trust; certificate replacement keeps old trust until the
613
639
  new preference is committed. If the bridge stops, new connections can fall back
614
640
  to the original route; already-interrupted requests are not replayed. An App
615
641
  already using the saved address need not be relaunched just because CCDX restarts.
616
- 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.
617
643
  `CCDX_AUTO_LAUNCH=0` keeps automatic launch disabled and never hot-attaches a
618
644
  running App. An already-persisted direct-environment preference can still be read
619
645
  when the App is manually opened.
@@ -683,7 +709,7 @@ to gain this endpoint; the new CLI cannot hot-upgrade an old Node process.
683
709
  Repair reports bridge readiness separately from the inspected App launch route.
684
710
  If a running App has no verified route, fix returns a partial result (exit 1), preserves
685
711
  its process and asks for a normal full quit followed by `ccdx`. A closed App is not
686
- 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
687
713
  that gray text appeared. Normal replies, image setup and account state are not changed.
688
714
  Unavailable/ambiguous process inspection reports `route_unverified` (exit 1), not
689
715
  a definite missing route or an instruction to restart an otherwise healthy App.
@@ -808,7 +834,7 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
808
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 |
809
835
  | `CCDX_IMG_CACHE_MAX_BYTES` | `67108864` | Process-local byte ceiling for cached image transforms; set to `0` to disable the cache |
810
836
  | `CCDX_DISABLE_IMG_OPT` | unset | Set to `1` to disable image optimization |
811
- | `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 |
812
838
  | `CCDX_GITHUB_TOKEN` | unset | Explicit GitHub Copilot OAuth token to validate and import before Device Flow |
813
839
  | `CCDX_GITHUB_TOKEN_PATH` | unset | Explicit file containing a GitHub Copilot OAuth token |
814
840
  | `CCDX_GITHUB_TOKEN_PATHS` | unset | Multiple token files separated by the platform path delimiter (`:` on macOS, `;` on Windows) |
@@ -941,7 +967,7 @@ MIT
941
967
  | --- | --- |
942
968
  | `ADAPTER_HOST` | Listener host; default loopback |
943
969
  | `ADAPTER_PORT` | Main listener port; default 2026 |
944
- | `CCDX_AUTO_LAUNCH` | Set to 0 to skip opening Codex |
970
+ | `CCDX_AUTO_LAUNCH` | Override saved automatic Codex opening; default off |
945
971
  | `CCDX_M365` | Set to 0 to disable the company source for this run |
946
972
  | `CCDX_USAGE_PATH` | Recorded usage file path |
947
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.4",
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"])
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;
@@ -13,6 +13,7 @@ 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,7 +37,7 @@ 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();
@@ -70,6 +71,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
70
71
  const match=/^\/v1internal(?::|\/)([A-Za-z][A-Za-z0-9]*)$/.exec(route);
71
72
  if(!local.pathname.startsWith(PREFIX+"/")||!match)throw httpError("Unknown Antigravity endpoint",404);
72
73
  const method=match[1];
74
+ if(controlMethods.has(method))applicationEvidence?.notice(req,res,"antigravity","control");
73
75
  if(req.method==="POST"&&!/^application\/json(?:;|$)/i.test(req.headers["content-type"]||""))throw httpError("Antigravity requires JSON",415);
74
76
  phase="admission";release=await measureRequestStageAsync("admission",()=>acquireRequest(req,{signal:abort.signal}));
75
77
  phase="body";abort.setTimeout(requestBodyTimeoutMs,"request_body_timeout");
@@ -96,10 +98,15 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
96
98
  }
97
99
  const open=async(value,options={})=>{
98
100
  const internal=options.internal===true,path=internal?"/v1internal:streamGenerateContent?alt=sse":route+local.search;
99
- if(generation){abort.setTimeout(upstreamTimeoutMs,"upstream_timeout");markUpstreamStarted(internal||method==="streamGenerateContent")}
100
- const result=await fetchGoogle(googleOrigin+path,{method:internal?"POST":req.method,headers:{...nativeHeaders(req),...(value?{"content-type":"application/json"}:{}),...(internal?{accept:"text/event-stream"}:{})},
101
- ...(value?{body:JSON.stringify(value)}:{}),signal:options.signal||abort.signal,redirect:"error"});
102
- 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;
103
110
  };
104
111
  phase="upstream";
105
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")]),
@@ -121,17 +128,19 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
121
128
  const response=value?.response||value,event=googleUsageEvent(value);if(event)captureUsage(event);
122
129
  const candidates=response?.candidates||[];
123
130
  if(candidates.some(candidate=>candidate.content?.parts?.some(part=>part.functionCall||!part.thought&&typeof part.text==="string"&&part.text)))markFirstOutput("delta");
124
- if(response?.error)outcome="failed";
131
+ if(response?.error){outcome="failed";sourceResponseFailed(upstream)}
125
132
  else if(outcome!=="failed"&&candidates.some(candidate=>candidate.finishReason)){
133
+ sourceResponseAccepted(upstream);
126
134
  outcome=candidates.every(candidate=>candidate.finishReason==="STOP")?"completed":"incomplete";
127
135
  }
128
136
  }}):null;
129
137
  res.writeHead(upstream.status,safeUpstreamResponseHeaders(upstream.headers));
130
138
  try{
131
- if(upstream.body)for await(const data of upstream.body){
132
- abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout");observer?.push(data);
133
- if(!await writeOrDrain(res,data,{signal:abort.signal}))throw httpError("Antigravity client disconnected",499);
134
- }
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)}}
135
144
  }finally{if(observer?.finish().unavailable&&!usageEvent)markRequestObservation({usage_state:"unavailable"})}
136
145
  if(generation&&!upstream.ok)outcome="failed";
137
146
  if(outcome)markResponseTerminal(outcome,upstream.ok?undefined:{origin:"upstream_http"});
@@ -163,7 +172,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
163
172
  const query=searchQuery(request),input={id:randomUUID(),commands:{search_query:[{q:query}]}};
164
173
  session=privacy?.prepareSession?await privacy.prepareSession(input,{protocol:"search",client:"gemini",signal:abort.signal}):passthrough(input);
165
174
  const response=await searchFn(session.body,{signal:abort.signal});
166
- 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)}
167
176
  const result=session.restoreValue(JSON.parse(await readBoundedResponseText(response,{maxBytes:8*1024*1024,signal:abort.signal,label:"Copilot search"})));
168
177
  markResponseTerminal("completed");
169
178
  res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response:groundedSearch(result,query)}));return;
@@ -181,14 +190,15 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
181
190
  converted=antigravityToChat(request,{model:target.model,effort:target.effort,reasoningEfforts:target.effort?[target.effort]:[],stream});
182
191
  markResponseModel(target.model);markRequestObservation({usage_state:"pending"});
183
192
  session=privacy?.prepareSession?await privacy.prepareSession(converted.chat,{protocol:"chat",client:"gemini",signal:abort.signal}):passthrough(converted.chat);
184
- 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")};
185
194
  phase="upstream";
186
195
  const upstream=compacting&&compaction?await compaction.run({body:session.body,protocol:"chat",scope:JSON.stringify(["gemini","github",compactionProfile()]),source:"github",client:"gemini",
187
196
  inputLimit:target.maxTokens,outputAllowance:session.body.max_completion_tokens||session.body.max_tokens||0,native:client.chatCompletions,options:callOptions,
188
197
  summarize:compactionSummarizer(session.body,"chat",client.chatCompletions),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await client.chatCompletions(session.body,callOptions);
189
198
  releaseInput();
190
199
  markUpstreamHeaders(upstream.status);
191
- if(!upstream.ok){markResponseErrorOrigin("upstream_http");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)}
192
202
  if(!stream){
193
203
  const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));captureUsage(data);
194
204
  const result=chatToAntigravity(data,converted.originalNames);markToolActivity(result,"gemini");
@@ -215,8 +225,10 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
215
225
  else if(phase==="admission")error=Object.assign(httpError(error.message,error.statusCode||503),{code:"ccdx_request_admission_unavailable"});
216
226
  if(typeof error.code==="string"&&error.code.startsWith("ccdx_compaction_"))res.setHeader("x-should-retry","false");
217
227
  counts.failed++;
218
- outcome=abort.signal.aborted&&["client_closed","client_aborted"].includes(abort.reason)?"cancelled":"failed";
219
- const origin=outcome==="cancelled"?"client_disconnect":currentRequestContext()?.errorOrigin||(abort.reason||phase==="admission"?"transport":error.origin==="privacy"?"privacy":error.statusCode<500?"client_validation":"transport");
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");
220
232
  markResponseErrorOrigin(origin);markResponseTerminal(outcome,{origin});
221
233
  if(res.headersSent&&!res.writableEnded&&!res.destroyed){res.end("data: "+JSON.stringify({error:{code:error.statusCode||502,message:error.message}})+"\n\n");}
222
234
  else sendJsonError(res,error,error.statusCode||502);
@@ -231,7 +243,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
231
243
  markRequestObservation({input_tokens:record.usage?.input_tokens,cached_input_tokens:record.usage?.cached_input_tokens});
232
244
  const context=currentRequestContext();
233
245
  recordUsageFn({...record,provider:usageProvider,client:"gemini",request_id:context?.requestId,requested_model:context?.requestedModel,
234
- outcome:outcome||"unknown",...(outcome!=="completed"?{partial:true}:{})});
246
+ outcome:outcome||"unknown",...(outcome!=="completed"||abort.signal.aborted?{partial:true}:{})});
235
247
  }
236
248
  }
237
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);
@@ -22,7 +22,7 @@ import {antigravityCopilotModels} from "./antigravity-models.mjs";
22
22
  const execute=promisify(execFile),key="gemini_antigravity_enabled",modelKey="gemini_antigravity_models";
23
23
 
24
24
  export function createAntigravityRuntime({client,models=()=>[],refreshModels,privacy,home=os.homedir(),env=process.env,inspect=inspectGeminiApp,
25
- exec=execute,searchFn,imageFn,guardSource,googleFetch,acquireRequest,readToken=()=>readSavedGithubToken(home),...timeouts}={}) {
25
+ exec=execute,searchFn,imageFn,guardSource,googleFetch,acquireRequest,applicationControl,readToken=()=>readSavedGithubToken(home),...timeouts}={}) {
26
26
  const options={home,env},guard=createConversationSourceGuard(options);
27
27
  const web=searchFn?null:createCopilotWeb({client,readToken});
28
28
  let app={status:"unknown"},route=null,lastOperation=null,compactionSalt;const conversationSources=new Map();
@@ -69,7 +69,9 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
69
69
  }
70
70
  const expected=listed.filter(model=>model.selected).map(model=>model.id).sort();
71
71
  const reload=config.enabled&&sourceEnabled?(activity.catalog_models===null?null:JSON.stringify([...activity.catalog_models].sort())!==JSON.stringify(expected)):false;
72
- return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,models_reload_required:reload,app,route_observed:handler.snapshot().observed,
72
+ const current=applicationControl?.snapshot().antigravity;
73
+ const visibleApp=current?{status:current.status,version:current.version||null,pids:current.pid?[current.pid]:[]}:app;
74
+ return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,models_reload_required:reload,app:visibleApp,application:current||null,route_observed:handler.snapshot().observed,
73
75
  model_source:"Google + GitHub Copilot",background_source:"GitHub Copilot",ordinary_chat_source:"Google (unchanged)",
74
76
  compaction_source:"Observed conversation source; existing background policy when unassigned",
75
77
  models:listed,model_groups:[...groups.values()],activity,last_operation:lastOperation};
@@ -98,10 +100,18 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
98
100
  withFileLockSync(file+".lock",()=>{const saved=readUserSettings({...options,strict:true});atomicWriteFileIfChangedSync(file,JSON.stringify({...saved,[key]:operation==="enable"},null,2)+"\n",{mode:0o600})});
99
101
  lastOperation=null;
100
102
  }
103
+ if(applicationControl){
104
+ if(operation==="open"){
105
+ const result=await applicationControl.action({id:"antigravity",operation:"open"});lastOperation={action:operation,status:result.status};
106
+ }else if(operation==="preview"){
107
+ const plan=await applicationControl.previewAntigravity();lastOperation={action:operation,status:plan.status,...(plan.status==="prepared"?{plan:{command:plan.command,args:plan.args}}:{})};
108
+ }else await applicationControl.check("antigravity",true);
109
+ return snapshot();
110
+ }
101
111
  app=await inspect();route=baseUrl+"/antigravity";
102
112
  if(["open","preview"].includes(operation)){
103
113
  const config=settings();
104
- const plan=config.enabled?planGeminiAppLaunch(app,{cloudCodeUrl:route,env}):app.status==="stopped"?{status:"prepared",command:"/usr/bin/open",args:["-a",app.app]}:{status:app.status==="running"?"needs_app_relaunch":app.status};
114
+ const plan=config.enabled?planGeminiAppLaunch(app,{cloudCodeUrl:route,env,home}):app.status==="stopped"?{status:"prepared",command:"/usr/bin/open",args:["-a",app.app]}:{status:app.status==="running"?"needs_app_relaunch":app.status};
105
115
  lastOperation={action:operation,status:plan.status};
106
116
  if(operation==="open"&&plan.status==="prepared"){
107
117
  await exec(plan.command,plan.args,{encoding:"utf8",timeout:5000,maxBuffer:4096});lastOperation.status="opened";app={...app,status:"starting"};
@@ -0,0 +1,43 @@
1
+ import { createHash } from "node:crypto";
2
+ import { claudeClientPaths, M365_CLAUDE_PROFILE_ID } from "./claude-client-config.mjs";
3
+ import { codexPaths } from "./codex-paths.mjs";
4
+ import { parseCodexToml } from "./config-toml.mjs";
5
+ import { readBoundedFile } from "./bounded-file.mjs";
6
+ import { userSettingsPath } from "./user-settings.mjs";
7
+
8
+ const read = async file => JSON.parse(await readBoundedFile(file, { maxBytes: 1024 * 1024, encoding: "utf8" }));
9
+ const sameUrl = (actual, expected) => { try { return new URL(actual).href.replace(/\/$/, "") === new URL(expected).href.replace(/\/$/, ""); } catch { return false; } };
10
+ const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === "object"
11
+ ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
12
+ const digest = value => createHash("sha256").update(JSON.stringify(canonical(value))).digest("hex");
13
+
14
+ // Inspect only integration fields; fingerprints stay in process memory.
15
+ export async function inspectApplicationConfiguration(id, { port = 2026, host = "127.0.0.1", ...options } = {}) {
16
+ let value, state;
17
+ try {
18
+ if (id === "claude_app") {
19
+ const paths = claudeClientPaths(options), [profile, meta, mode] = await Promise.all([read(paths.profile), read(paths.meta), read(paths.threep).catch(error => { if (error.code === "ENOENT") return {};throw error; })]);
20
+ value = { provider: profile.inferenceProvider, address: profile.inferenceGatewayBaseUrl, key: profile.inferenceGatewayApiKey,
21
+ models: typeof profile.inferenceModels === "string" ? JSON.parse(profile.inferenceModels) : profile.inferenceModels,
22
+ discovery: profile.modelDiscoveryEnabled, profile: meta.appliedId, hybrid: meta.hybridPointer,
23
+ mode: profile.disableDeploymentModeChooser === true || mode.deploymentMode !== "1p" ? "3p" : "1p" };
24
+ state = value.provider === "gateway" && value.profile === M365_CLAUDE_PROFILE_ID && !value.hybrid && value.mode === "3p" && typeof value.key === "string" && Boolean(value.key)
25
+ && sameUrl(value.address, `http://${host}:${port}/anthropic`) ? "configured" : "preserved";
26
+ } else if (id === "codex") {
27
+ const file = codexPaths(options).config;
28
+ const config = parseCodexToml(await readBoundedFile(file, { maxBytes: 2 * 1024 * 1024, encoding: "utf8" }));
29
+ value = { provider: config.model_provider, address: config.openai_base_url, models: config.model_catalog_json, gateway: config.model_providers?.ccdx_gateway,
30
+ model: config.model };
31
+ state = ((!value.provider || value.provider === "openai") && sameUrl(value.address, `http://${host}:${port}/v1`))
32
+ || (value.provider === "ccdx_gateway" && sameUrl(value.gateway?.base_url, `http://${host}:${port}/v1`)) ? "configured" : "preserved";
33
+ } else {
34
+ let settings;try { settings = await read(userSettingsPath(options)); } catch (error) { if (error.code !== "ENOENT") throw error;settings = {}; }
35
+ value = { enabled: settings.gemini_antigravity_enabled === true, models: settings.gemini_antigravity_models || null, port, host };
36
+ state = value.enabled ? "configured" : "native";
37
+ }
38
+ const reload = { ...value };delete reload.key;
39
+ return { state, revision: digest(value), reloadRevision: digest(reload) };
40
+ } catch (error) {
41
+ return { state: error.code === "ENOENT" ? "not_configured" : "unavailable", revision: "unknown" };
42
+ }
43
+ }