codex-copilot-dx 1.3.24 → 1.3.26
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.
- package/README.md +3 -3
- package/docs/ARCHITECTURE.md +25 -14
- package/docs/README.md +6 -16
- package/docs/REFERENCE.md +30 -4
- package/package.json +1 -1
- package/src/antigravity-chat-bridge.mjs +3 -1
- package/src/antigravity-handler.mjs +71 -15
- package/src/antigravity-runtime.mjs +11 -3
- package/src/antigravity-usage.mjs +86 -0
- package/src/cli-command-spec.mjs +9 -4
- package/src/cli-management.mjs +25 -5
- package/src/connection-view.mjs +1 -3
- package/src/dashboard/connections.js +48 -29
- package/src/dashboard/flow.js +12 -11
- package/src/dashboard/gemini.js +67 -39
- package/src/dashboard/index.html +30 -24
- package/src/dashboard/language.js +64 -27
- package/src/dashboard/status.js +3 -1
- package/src/dashboard/ui.css +2 -5
- package/src/dashboard/ui.js +20 -9
- package/src/dashboard/usage.js +35 -19
- package/src/dashboard-api.mjs +19 -6
- package/src/live-models.mjs +14 -4
- package/src/provider-runtime.mjs +2 -3
- package/src/stream-performance.mjs +5 -1
- package/src/terminal-state.mjs +8 -0
- package/src/usage-analysis.mjs +19 -8
- package/src/usage-analytics.mjs +9 -7
- package/src/usage-query.mjs +36 -0
- package/src/usage-store.mjs +4 -3
- package/src/usage.mjs +7 -3
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Use your model services in **Codex App, Claude App and Claude Code** through one local gateway.
|
|
4
4
|
|
|
5
|
-
On macOS, the optional Gemini integration adds Copilot Carbon and Argon to the original App's Antigravity. Ordinary Gemini chat keeps Google.
|
|
5
|
+
On macOS, the optional Gemini integration adds Copilot Carbon and Argon to the original App's Antigravity. Ordinary Gemini chat keeps Google. The Antigravity page lists each model once, with its reasoning choices on the same row. Inspect it with `ccdx app antigravity status`. Existing clients keep their setup.
|
|
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
|
|
|
@@ -30,7 +30,7 @@ On Windows, use `npm.cmd` or `ccdx.cmd` if PowerShell blocks npm-generated scrip
|
|
|
30
30
|
|
|
31
31
|
The Web UI opens at [http://127.0.0.1:2026](http://127.0.0.1:2026/). Run `ccdx web` to open it again, including before signing in.
|
|
32
32
|
|
|
33
|
-
1. **Model sources:** connect an account or API, read its models
|
|
33
|
+
1. **Model sources:** connect an account or API, read its models, choose allowed apps and save. Source tabs only change the view.
|
|
34
34
|
2. **Codex / Claude:** choose visible models, set a default and save. Preview and synchronize client settings when needed.
|
|
35
35
|
3. **Overview / Requests:** check configuration, activity and errors.
|
|
36
36
|
4. **Usage → Context:** inspect reported input, model windows and observed compactions from this run.
|
|
@@ -52,7 +52,7 @@ Model availability depends on your account and service. Microsoft 365 also requi
|
|
|
52
52
|
| Preview client setup | `ccdx app claude-app sync --preview` |
|
|
53
53
|
| Set up Antigravity | `ccdx app antigravity status` / `enable` / `open` |
|
|
54
54
|
| Inspect failures | `ccdx requests --failed` |
|
|
55
|
-
| Read usage | `ccdx usage` / `ccdx usage --scope run` |
|
|
55
|
+
| Read usage | `ccdx usage` / `ccdx usage --provider google --days 7` / `ccdx usage --scope run` |
|
|
56
56
|
| Inspect preferences | `ccdx config show --effective` |
|
|
57
57
|
| Inspect local masking | `ccdx config privacy status` |
|
|
58
58
|
| Check local setup | `ccdx doctor` |
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -17,6 +17,15 @@ Client integration, image tools and the dashboard are not a general plugin frame
|
|
|
17
17
|
|
|
18
18
|
## Gemini native boundary
|
|
19
19
|
|
|
20
|
+
`antigravity-usage.mjs` observes Google JSON/SSE within the original forwarding loop, with the existing SSE byte limit and no stream tee or read-ahead. Observation failures mark usage unavailable and never change response bytes. The handler coalesces reported numeric fields and settles one usage row per request, including usage received before failure/cancellation. Google candidate/thought output and prompt/tool-use input are normalized without treating missing cache counts as zero. Request ID, original model, actual model and usage availability are scalar metadata; prompts and response text are not persisted by this observer.
|
|
21
|
+
|
|
22
|
+
The management snapshot keeps native per-effort aliases in `models` and adds `model_groups` for one model row with several reasoning choices. Saved alias subsets and the native catalog are unchanged. The WebUI and terminal group the display and selection while JSON clients retain the compatible alias list.
|
|
23
|
+
|
|
24
|
+
Antigravity tool schemas are converted to Chat Completions schemas. Object schemas always include an explicit `properties` map, including zero-argument functions. The upstream Copilot service rejects native schemas that omit that map. Pausing Copilot access keeps model choices visible while generation remains gated.
|
|
25
|
+
|
|
26
|
+
The dashboard separates source enablement, source-to-app authorization and per-app model choices. Source enablement is immediate; authorization and model drafts use explicit Save / Discard actions. GitHub, Microsoft 365 and custom APIs share the same authorization form. Antigravity's source authorization and its Copilot access switch represent the same saved integration state.
|
|
27
|
+
|
|
28
|
+
|
|
20
29
|
`gemini-app.mjs` verifies the installed App and prepares a process-local
|
|
21
30
|
`CLOUD_CODE_URL` launch without editing its bundle or closing a running App.
|
|
22
31
|
`antigravity-runtime.mjs` owns explicit enablement, source-history protection and
|
|
@@ -40,7 +49,7 @@ No independent WebKit client or private WebKit SPI is included.
|
|
|
40
49
|
|
|
41
50
|
## Composition and lifecycle
|
|
42
51
|
|
|
43
|
-
### Manual connection graph
|
|
52
|
+
### Manual connection graph
|
|
44
53
|
|
|
45
54
|
`provider-runtime.mjs` composes built-in lifecycle with `connection-runtime.mjs`,
|
|
46
55
|
which owns grants, switches, versioned model-deployment bindings and lifecycle. `access-settings.mjs`
|
|
@@ -548,6 +557,8 @@ projects the optional lightweight response; full status stays the default public
|
|
|
548
557
|
contract. Hidden status regions defer DOM updates, and summary rendering never
|
|
549
558
|
replaces the full request/history cache.
|
|
550
559
|
|
|
560
|
+
`usage-query.mjs` defines provider/model and inclusive calendar-date selection for the WebUI and CLI. `usage-analysis.mjs` keys its existing bounded cache by that selection and applies the same predicate to full scans and witnessed appends. Model choices are collected before the predicate so changing a filter does not lose the other options. Tables, totals and charts consume one filtered snapshot. Up to 365 daily points remain bounded; older valid records share an earlier bucket, preserving all-history totals without unbounded DOM growth. Chart type and language changes remain local; changes to source, model or period invalidate only usage.
|
|
561
|
+
|
|
551
562
|
`dashboard/usage.js` owns bar/curve geometry and viewport-gated, one-shot Web Animations. The two views share retained analytics and accessible day buttons; their paths never connect unavailable history or overshoot adjacent values. View-only changes leave the calendar nodes intact. The UI lifecycle cancels motion on hidden/suspended views and reduced-motion changes; no animation timer or chart dependency is added. `usage-store.mjs` shares cache-evidence validation between retained summaries and process-local totals. It keeps paired input/cache-read sums and known/unknown record counts separate from full token totals; CLI/TUI, WebUI and daily analytics use those same sums for the weighted rate and partial-coverage flag. Aggregate snapshots expose that basis without new persistence or log scans. The Overview renderer formats that snapshot and preserves unknown/invalid values.
|
|
552
563
|
|
|
553
564
|
`dashboard-updates.mjs` is loaded only by the protected update-information route. It projects bounded public stable-release metadata and publication dates, with process-local single-flight, five-minute success and one-minute failure caches. Its asynchronous npm network-configuration read reuses the installer's existing policy-preserving downloader; it adds no runtime dependency, credentials or synchronous child process on the service event loop. Metadata has a four-second per-request deadline and 128 KiB decoded-body bound. It never installs or restarts anything and does not alter startup's independent web-redirect lookup. `dashboard/updates.js` renders current/available/unknown states and validated, pinned installation command text; `refresh.js` owns its visible Settings refresh cadence. Failed checks preserve explicitly labeled prior metadata. No provider authentication or inference is involved.
|
|
@@ -703,19 +714,19 @@ workflow and GitHub Release must deliver those same package bytes. WebUI source
|
|
|
703
714
|
selection and Auto Review remain under Codex; M365 lifecycle stays in source
|
|
704
715
|
management. CLI and UI share advertised effort filtering and preference writes.
|
|
705
716
|
|
|
706
|
-
## Independent appearance settings
|
|
717
|
+
## Independent appearance settings
|
|
707
718
|
|
|
708
719
|
Web color (`green` / `klein` / `pink` / `mono`) and dark/light mode are browser-local presentation state applied before CSS in `dashboard/theme.js`. CSS semantic roles keep errors/warnings separate from theme accents. Terminal color (`green`, `klein`, `pink`, `mono`, `orange`) uses a distinct `terminal_color_theme` config field; animation continues to use `terminal_animation`. `terminal-colors.mjs` owns terminal color capability checks and escaping, while the existing layout runs on plain text first. The one-per-second coherent settings snapshot carries terminal color; animation frames introduce no additional settings reads. No inference, provider-routing or installer dependency is added.
|
|
709
720
|
|
|
710
721
|
The existing same-origin bounded settings action saves terminal color through the strict locked atomic writer, then applies it to the live console. Read or save failures retain existing files and controls revert to the last confirmed choice. Model-list check errors project only bounded public diagnostic fields; UI associates them with the selected source and its last successful snapshot. Existing generation checks, cancellation and deduplication prevent late results from replacing another source's data.
|
|
711
722
|
|
|
712
|
-
## Activity presentation and Messages timing
|
|
723
|
+
## Activity presentation and Messages timing
|
|
713
724
|
|
|
714
725
|
The existing status payload projects `model_activity.active` from the three fixed inference route counters plus actual image-generation activity, never total HTTP activity or image MCP calls. It adds no history store, provider request or listener. `dashboard/activity.js` consumes this metadata through the existing refresh path, expires stale evidence after six seconds and pauses offscreen animation. Idle, active and unknown remain distinct; CSS owns six theme-colored dots and the idle-only halo. Terminal Cache hit reads the existing raw runtime aggregate rather than deriving a ratio from rounded display numbers.
|
|
715
726
|
|
|
716
727
|
The Claude gateway still relays original native SSE bytes. `stream-performance.mjs` classifies only nonempty text, thinking and tool-argument deltas as first output; empty and signature-only deltas remain transport metadata. Sparse/interleaved blocks are not reordered or translated. Existing provider generations, locked atomic settings writes, cancellation and route ownership remain the composition boundaries.
|
|
717
728
|
|
|
718
|
-
## Dashboard layout and information scopes
|
|
729
|
+
## Dashboard layout and information scopes
|
|
719
730
|
|
|
720
731
|
The existing CSS grid reserves explicit header/body/footer tracks; the body owns spare space from the full-height sidebar. The header uses an opaque themed sticky surface, stable action slots and a deliberate compact toolbar. Scrollbar space is stable, with an always-scroll fallback for older engines. `console.js` owns route titles, scroll reset and main-content focus; refresh code does not navigate or reset scroll.
|
|
721
732
|
|
|
@@ -723,7 +734,7 @@ The eight existing views remain. `status.js` groups Overview clients by applicat
|
|
|
723
734
|
|
|
724
735
|
HTML owns grouping: Codex buffer maintenance is separate from request performance, usage filters sit with the data they actually control, Requests prioritizes recent records and folds bounded technical fields into each row, and Checks & repairs owns runtime diagnostics. Settings owns preferences and updates. Request expansion is preserved by bounded request keys, and literal upstream values still use text nodes. Existing settings transactions, same-origin protections and confirmations remain in use; action failures target the affected controls. No framework, runtime dependency, endpoint, log scan, model call or installer policy is added.
|
|
725
736
|
|
|
726
|
-
## Catalog failure evidence and controls
|
|
737
|
+
## Catalog failure evidence and controls
|
|
727
738
|
|
|
728
739
|
`providers/m365-catalog-diagnostic.mjs` classifies model-list HTTP failures using
|
|
729
740
|
fixed causes. The one known Entra-disabled message is recognized exactly; other
|
|
@@ -743,7 +754,7 @@ in per-model details. Usage trends and summaries are peer panels, still loaded o
|
|
|
743
754
|
demand. Saved/effective preference differences are shown only when relevant.
|
|
744
755
|
|
|
745
756
|
|
|
746
|
-
## Active request projection and restrained motion
|
|
757
|
+
## Active request projection and restrained motion
|
|
747
758
|
|
|
748
759
|
`stream-performance.mjs` remains the timing/outcome owner. Each metrics instance
|
|
749
760
|
retains at most 64 active snapshot closures; `finish` removes them idempotently.
|
|
@@ -779,7 +790,7 @@ the last row and following details use whitespace. Programmatic main-content
|
|
|
779
790
|
focus has no frame; interactive keyboard focus remains visible.
|
|
780
791
|
|
|
781
792
|
|
|
782
|
-
## Flow layout and client-hint correction
|
|
793
|
+
## Flow layout and client-hint correction
|
|
783
794
|
|
|
784
795
|
`request-application.mjs` normalizes bounded scalar hints using an explicit map.
|
|
785
796
|
The map now recognizes `Codex Desktop`, observed in local desktop session metadata
|
|
@@ -805,7 +816,7 @@ styling keeps the M365 navigation link semantically a link while matching the
|
|
|
805
816
|
existing GitHub shortcut; wording describes navigation rather than a silent check.
|
|
806
817
|
No new polling, framework, runtime dependency, setting or endpoint is introduced.
|
|
807
818
|
|
|
808
|
-
## Catalog transactions and default identity
|
|
819
|
+
## Catalog transactions and default identity
|
|
809
820
|
|
|
810
821
|
GitHub dashboard catalog reads use the existing `profile-model-runtime.mjs` single-flight through an injected refresh callback, rather than a second independent directory request. Successful publication updates the shared provider registry/endpoint cache, and the dashboard rereads connection candidates while preserving drafts. Explicit reads report refresh failures instead of presenting the last-good fallback as fresh success. Credential changes during a read reject publication; catalog browsing never synchronizes client files or changes selected deployments, defaults, grants or native authentication.
|
|
811
822
|
|
|
@@ -986,7 +997,7 @@ Geometry and SVG identity reuse from 1.2.23 remain in place, with hidden/stale/
|
|
|
986
997
|
reduced-motion behavior and summary tables preserved.
|
|
987
998
|
|
|
988
999
|
|
|
989
|
-
## Model presentation and shared source impact
|
|
1000
|
+
## Model presentation and shared source impact
|
|
990
1001
|
|
|
991
1002
|
`model-display.mjs` is a pure presentation fallback. `api-model-display.mjs` retains bounded upstream names beside maker declarations in the existing revision-bound, rebuildable cache. `providers/api.mjs` exposes that evidence to `client-model-plan.mjs`, which disambiguates presentation independently of route identity. Claude uses labelOverride for client aliases regardless of the default source. No connection-schema or routing-ID migration is introduced. Existing client-file ordering and manual ownership remain authoritative.
|
|
992
1003
|
|
|
@@ -1052,7 +1063,7 @@ Source-catalog tables keep fixed column geometry while native disclosures expand
|
|
|
1052
1063
|
|
|
1053
1064
|
A full snapshot keeps a local map of compiled client plans, including reuse during source-impact projection. Public data remains cloned and contains the same revisions/route identifiers. No persistent or global cache is added. `updateAccessSettings` retains strict validation, the lock and original-byte v1 backup, then skips an atomic rewrite only when serialized bytes already match. Skipping a file write does not skip an explicit control action or client sync.
|
|
1054
1065
|
|
|
1055
|
-
The CLI keeps only command/version/status fundamentals before its early command dispatch. Existing tool implementations are imported in their branches; startup composition loads afterward in its previous dependency order. Native account stores, source/key identity, model projections and image/prediction behavior are unchanged.
|
|
1066
|
+
The CLI keeps only command/version/status fundamentals before its early command dispatch. Existing tool implementations are imported in their branches; startup composition loads afterward in its previous dependency order. Native account stores, source/key identity, model projections and image/prediction behavior are unchanged.
|
|
1056
1067
|
|
|
1057
1068
|
### Context observations
|
|
1058
1069
|
|
|
@@ -1160,13 +1171,13 @@ Claude App 3.x and 4.x share the inspected effort-capable adapter. Later unknown
|
|
|
1160
1171
|
|
|
1161
1172
|
Usage presentation maps configured api_ identifiers to current provider labels after aggregation. Rows, chart filters and historical statistics keep their original keys. Provider-label changes refresh only the table/model labels, preserving the selected raw model key, day and existing chart nodes. The native capability replay disables usage persistence and gives its process a temporary usage path; no production filter recognizes test model names or response IDs.
|
|
1162
1173
|
|
|
1163
|
-
## Native image recovery and request correlation
|
|
1174
|
+
## Native image recovery and request correlation
|
|
1164
1175
|
|
|
1165
1176
|
`image-control.mjs` owns explicit check/repair/open operations for WebUI and terminal commands, reusing client configuration, host preparation and the existing prediction-aware launcher. Repair cannot kill an App or start another service. `image-host-state.mjs` retains bounded, process-local host evidence; the stdio bridge reports initialization and successful new-thread registration through the protected same-origin settings channel without blocking model traffic. Reporter work is bounded and aborted when the original CLI exits. Runtime evidence never contains prompts, images, paths or raw chat identifiers and cannot establish registration in unobserved chats. Manual loopback checks echo a nonce and explicitly identify their Node-only scope.
|
|
1166
1177
|
|
|
1167
1178
|
The existing salted session observation is projected into request metadata. Active requests can reference the previous retained request from the same anonymous session, application and provider; this does not change request routing, history or tool caches. Chat endpoint recognition accepts both `/chat/completions` and `/v1/chat/completions`. Bare JSON error lines in a Messages event stream terminate with an explicit protocol diagnostic rather than waiting for message_stop; normal SSE frames retain their bytes.
|
|
1168
1179
|
|
|
1169
|
-
## Boundary reliability
|
|
1180
|
+
## Boundary reliability
|
|
1170
1181
|
|
|
1171
1182
|
Native image failures cancel the vendor response and project safe JSON; API Responses compatibility consumes the existing sanitized error once and retains its metadata. Image history collection records whether the current container appended references instead of rescanning previous containers.
|
|
1172
1183
|
|
|
@@ -1174,7 +1185,7 @@ The stdio host uses a paused-source line pump only while a destination is blocke
|
|
|
1174
1185
|
|
|
1175
1186
|
`bounded-file.mjs` and `atomic-file.mjs` provide asynchronous bounded reads and durable single/paired writes for request-path state. Other synchronous configuration callers retain their APIs. Conversation admission and company-account guards use abortable asynchronous lock waiting with their prior timeout/stale policy. Messages transfer plans reserve in-process ownership while committing; primary and marker writes retain rollback behavior. JSON/SSE delivery awaits the applicable commit, and settled source checks keep a synchronous cached path. No new cache, file format or provider-selection policy is introduced.
|
|
1176
1187
|
|
|
1177
|
-
## Shared Codex App restart and source reliability
|
|
1188
|
+
## Shared Codex App restart and source reliability
|
|
1178
1189
|
|
|
1179
1190
|
The image and input-suggestion panels share `codex-launch-control.mjs`. `codex-app-control.mjs` associates live host reports with the verified macOS App by process ancestry and checks its prediction PAC argument without treating another process's host or an unobserved chat as proof. Its AppKit control targets only the verified bundle path and PID. A restart requires an explicit user action, prepares enabled routes, asks the App to quit normally, waits for exit, applies any pending prediction display setting and then uses the existing launcher. A refusal, unknown identity, multiple Apps or timeout stops the action without force-quit. A failed post-close display write stays pending and is reported after the App is reopened. Host evidence is accepted independently of serialized settings operations so a restarting App's short-lived report is not lost behind its own restart. Later host tool events also re-establish evidence if CCDX restarted while the host remained live.
|
|
1180
1191
|
|
|
@@ -1182,7 +1193,7 @@ The managed Codex catalog projects explicit source input modalities ahead of nat
|
|
|
1182
1193
|
|
|
1183
1194
|
`safe-upstream-error.mjs` reads only failed image or custom API responses, with a 64 KiB size bound, a 200 ms timer and four concurrent readers. Only fixed code/status pairs and local messages escape the reader. Original status, stable CCDX codes and validated Retry-After remain intact. Error-header callbacks normally release request admission before the optional body read; an eligible explicit compatibility rejection retains admission through its one retry. Image processing slots are released before their error read. Count-token singleflight forwards callbacks only to the appropriate waiters. Successful requests never invoke the reader.
|
|
1184
1195
|
|
|
1185
|
-
## Client updates and streaming boundaries
|
|
1196
|
+
## Client updates and streaming boundaries
|
|
1186
1197
|
|
|
1187
1198
|
`client-versions.mjs` inspects bounded local App metadata asynchronously after service readiness. It coalesces checks, preserves a corrupt observation file, and atomically records only installed versions, builds and change times. A timed-out inspection cannot block service startup or inference. The current App process and actual capability adoption remain unverified. A detected unrecognized system Claude App major prevents later writes to shared capability fields without changing existing routing or model aliases. The existing model-refresh timer, manual checks and a nonblocking service-reuse notification schedule observation; a disabled timer leaves startup and manual checks available.
|
|
1188
1199
|
|
package/docs/README.md
CHANGED
|
@@ -1,19 +1,9 @@
|
|
|
1
1
|
# Documentation
|
|
2
2
|
|
|
3
|
-
- [Quick start](../README.md): install, connect sources and choose app models.
|
|
4
|
-
- [Reference](REFERENCE.md): commands, settings, diagnostics
|
|
5
|
-
- [Architecture](ARCHITECTURE.md):
|
|
6
|
-
- [
|
|
7
|
-
- [
|
|
8
|
-
- [1.3.5](RELEASE_1.3.5.md): protocol-first App checks, bounded prediction transport and incremental usage analytics.
|
|
9
|
-
- [1.3.4](RELEASE_1.3.4.md): centered Auto refresh labels at compact control heights.
|
|
10
|
-
- [1.3.3](RELEASE_1.3.3.md): live activity updates and compact WebUI spacing.
|
|
11
|
-
- [1.3.2](RELEASE_1.3.2.md): protected App keys, bounded diagnostics and coalesced usage reads.
|
|
12
|
-
- [1.3.1](RELEASE_1.3.1.md): bounded context observations and anchored WebUI details.
|
|
13
|
-
- [1.3.0](RELEASE_1.3.0.md): scope, compatibility changes and verification.
|
|
3
|
+
- [Quick start](../README.md): install CCDX, connect model sources and choose app models.
|
|
4
|
+
- [Reference](REFERENCE.md): current commands, settings, diagnostics and recovery.
|
|
5
|
+
- [Architecture](ARCHITECTURE.md): runtime ownership, protocols and security boundaries.
|
|
6
|
+
- [Current release](RELEASE.md): user-facing changes and unverified scope.
|
|
7
|
+
- [Benchmark fixtures](../scripts/fixtures/README.md): test-image provenance.
|
|
14
8
|
|
|
15
|
-
CLI help describes the installed package. The running service
|
|
16
|
-
|
|
17
|
-
Historical `RELEASE_*.md` files record their own source revision and test environment. They remain engineering evidence, not current installation instructions. GitHub Release cleanup does not remove Git history or npm versions.
|
|
18
|
-
|
|
19
|
-
[Benchmark fixtures](../scripts/fixtures/README.md) document test-image provenance.
|
|
9
|
+
CLI help describes the installed package. The running service uses its loaded version until its next normal restart. Historical release records remain in GitHub Releases and Git history.
|
package/docs/REFERENCE.md
CHANGED
|
@@ -38,7 +38,7 @@ For installation and first use, start with the [README](../README.md). This refe
|
|
|
38
38
|
| `ccdx config reset --preview` / `restore` | Preview defaults or restore the pre-reset backup |
|
|
39
39
|
| `ccdx requests [--failed] [--active]` | Inspect retained requests |
|
|
40
40
|
| `ccdx requests show <request_id>` | Read one retained request |
|
|
41
|
-
| `ccdx usage [--scope all\|run] [--provider ID]` | Read
|
|
41
|
+
| `ccdx usage [--scope all\|run] [--provider ID] [--model ID] [--days N\|all]` | Read filtered retained usage or current-run totals |
|
|
42
42
|
| `ccdx doctor [--online] [--compat] [--fix] [--json]` | Check local setup; optional access checks and repairs |
|
|
43
43
|
| `ccdx doctor config` / `network` / `report` | Read configuration, routing or a redacted local report |
|
|
44
44
|
| `ccdx doctor cache [--limit MiB\|default]` | Inspect runtime buffers or change their limit |
|
|
@@ -68,8 +68,15 @@ inspection. Use `app antigravity status` to check the signed installation explic
|
|
|
68
68
|
The old `app gemini` commands remain available. Authorize Antigravity on the GitHub
|
|
69
69
|
Copilot source page, or with `source github access --edit --apps codex,antigravity --yes`.
|
|
70
70
|
Choose its exposed models on the Antigravity page or with
|
|
71
|
-
`app antigravity models --edit`. A model
|
|
72
|
-
|
|
71
|
+
`app antigravity models --edit`. Each WebUI/terminal row represents one model; reasoning levels are independent choices in that row. A model checkbox selects or clears all its levels, and a mixed checkbox preserves a saved subset. Save/Discard, refresh, navigation and pausing keep that subset.
|
|
72
|
+
|
|
73
|
+
The native Gemini catalog still uses distinct routing aliases for each level so its original selector can choose the intended effort. JSON model output retains those aliases for compatibility, with a `model` field identifying the actual model; the management status also includes `model_groups`. A model file accepts `{"models":["gemini-4-carbon"]}` to expose all of its levels, or the existing `ccdx-copilot-...-low|medium|high` aliases to choose a subset.
|
|
74
|
+
After saving, the Antigravity page reports whether the client has fetched the current model list. If the list is pending, reopen Gemini through CCDX.
|
|
75
|
+
|
|
76
|
+
The WebUI uses one authorization form for GitHub Copilot, Microsoft 365 and custom APIs. Source switches apply immediately. App-authorization and model checkboxes are drafts until **Save**; **Discard changes** restores the saved selection. Drafts survive refresh and navigation. Source authorization does not choose app models.
|
|
77
|
+
|
|
78
|
+
Pausing Antigravity Copilot access retains its saved model selection. Native Google model routes remain available; Copilot models and all Antigravity background summaries, searches and images use Copilot. The connection indicator reports observed requests separately from enabled access, and connection activity includes discovery/control requests.
|
|
79
|
+
|
|
73
80
|
The page distinguishes enabled access from an observed client connection.
|
|
74
81
|
|
|
75
82
|
Carbon and Argon appear with Low, Medium and High reasoning levels when the
|
|
@@ -113,7 +120,7 @@ Clicking the Web UI logo plays one brief rotation and keeps its Overview navigat
|
|
|
113
120
|
|
|
114
121
|
Upgrades retain saved account bindings, source IDs, key references, model choices/defaults and capability overrides. Native account stores keep their existing owner; bookkeeping does not request another login. Unchanged client settings need no repeat save or synchronization. Explicit user changes and ordinary credential renewal keep their current behavior.
|
|
115
122
|
|
|
116
|
-
Sources own accounts, API addresses, keys and model capabilities. Apps own visible models and defaults. Allowing an app to use a source does not select all its models. Selecting no models pauses
|
|
123
|
+
Sources own accounts, API addresses, keys and model capabilities. The model directory lists protocol-compatible apps; local grants and exclusion details separately show whether an app may currently use a model. Apps own visible models and defaults. Allowing an app to use a source does not select all its models. Selecting no models pauses managed Codex/Claude conversation routing. Antigravity’s Copilot switch also controls its background requests. Settings owns service preferences and appearance, not model routing. An unchanged graph save keeps the file bytes and modification time; explicit sync, refresh and credential actions still run. Existing v1 configuration is backed up byte-for-byte before its first v2 write; reads do not migrate files.
|
|
117
124
|
|
|
118
125
|
In the Web UI, **Model sources → Add API** saves the source and immediately reads its catalog. A failed read keeps the saved source and editor. Select supported models and their declared interfaces before assigning them to apps. Table details expand downward without shifting their controls or redistributing columns, including request metadata and check results. API-editor capability details open below their model row; manual overrides are separate from reported metadata.
|
|
119
126
|
|
|
@@ -152,6 +159,25 @@ Catalog diagnostics distinguish local cached data from an online response and ex
|
|
|
152
159
|
|
|
153
160
|
Request inspection covers bounded retained records, not a full conversation archive. Unidentified clients stay unidentified. Routine diagnostics omit secrets, prompts and error bodies. Explicit error excerpts use bounded, redacted collection. The usage JSON `requests` field counts recorded usage rows, not HTTP calls. Usage is returned token metadata; cache hit is reused input divided by input from records with valid counts for both. Unknown/invalid records remain in token totals but are excluded from both sides of the rate, with partial coverage indicated. It is not a request-based cache rate or a billing receipt.
|
|
154
161
|
|
|
162
|
+
Antigravity Copilot answers/background summaries and native Google generation record returned Gemini token usage for JSON and streaming responses. Each request records its latest reported fields once, including usage received before failure or cancellation. Missing upstream token/cache counts remain unknown; a real zero cache count stays zero. This starts with 1.3.26; previously unrecorded usage cannot be recovered from the ledger. Ordinary Gemini chat remains outside the Antigravity bridge.
|
|
163
|
+
|
|
164
|
+
Native records use source `google`; Copilot records use `github`. Google output includes reported candidate and thought tokens, with thought tokens also identified separately. Reported tool-use prompt tokens are included in input; cached tokens remain a subset of input. The original Google response bytes, status and backpressure remain unchanged. Observation uses the existing SSE buffer limit per event or non-streaming response; oversized/unreadable metadata is marked unavailable and the response continues normally. Only numeric usage and routing metadata are retained.
|
|
165
|
+
|
|
166
|
+
Requests and usage share the CCDX request ID; an upstream response ID is separate. Request details show the original model when it differs from the actual model, and distinguish reported, partial, missing and unreadable usage metadata. Requests waiting for body parsing show “Model pending” and “Source pending”; queue, input processing, upstream wait and response delivery have separate states. The CLI exposes the same retained metadata with `ccdx requests show ID --format json`; `ccdx requests --app antigravity` filters the native integration.
|
|
167
|
+
|
|
168
|
+
Usage source, model and time controls apply to the entire token-usage page: totals, model rows and charts. Selecting a day narrows that shared query; Clear date restores the previous period. Chart type, language and theme changes remain local. All retained history remains available; date charts keep at most 365 daily points and combine earlier valid records into an Earlier records bucket. Invalid/future timestamps remain in all-history totals but are excluded from date charts and bounded date filters, with the exclusion count shown. Model choices are bounded to 100 and preserve other available choices while a filter is active.
|
|
169
|
+
|
|
170
|
+
CLI and TUI subcommands share the same source/model/calendar semantics:
|
|
171
|
+
|
|
172
|
+
```sh
|
|
173
|
+
ccdx usage --provider google --days 7
|
|
174
|
+
ccdx usage --model 'github / gemini-4-carbon' --from 2026-11-01 --to 2026-11-13 --time-zone Asia/Shanghai
|
|
175
|
+
ccdx usage --scope run --provider google
|
|
176
|
+
ccdx requests --app antigravity --active
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
`--days` accepts 1–365 or `all` (the default). Explicit inclusive `--from`/`--to` dates use YYYY-MM-DD and cannot be combined with a numeric `--days`. Dates use UTC by default; `--time-zone` chooses another IANA zone. An unqualified model includes matching models across sources; `source / model` narrows it to one source. Current-run totals support only the provider filter; model/date filters use retained history. The service TUI includes returned Google usage in its existing current-run totals without scanning the ledger.
|
|
180
|
+
|
|
155
181
|
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.
|
|
156
182
|
|
|
157
183
|
## Settings and appearance
|
package/package.json
CHANGED
|
@@ -30,6 +30,7 @@ function schemaForChat(schema) {
|
|
|
30
30
|
else if (schemaLists.has(key) && Array.isArray(value)) result[key] = value.map(schemaForChat);
|
|
31
31
|
else result[key] = value;
|
|
32
32
|
}
|
|
33
|
+
if (result.type === "object" && !Object.hasOwn(result, "properties")) result.properties = {};
|
|
33
34
|
return result;
|
|
34
35
|
}
|
|
35
36
|
|
|
@@ -178,7 +179,7 @@ export function chatToAntigravity(response, originalNames) {
|
|
|
178
179
|
...(usage ? { usageMetadata: { promptTokenCount: usage.prompt_tokens || 0, candidatesTokenCount: usage.completion_tokens || 0, totalTokenCount: usage.total_tokens || 0 } } : {}) };
|
|
179
180
|
}
|
|
180
181
|
|
|
181
|
-
export async function* chatStreamToAntigravity(response, originalNames, { onChunk } = {}) {
|
|
182
|
+
export async function* chatStreamToAntigravity(response, originalNames, { onChunk, onUsage } = {}) {
|
|
182
183
|
if (!response?.body) throw invalid("Upstream Chat stream has no body", 502);
|
|
183
184
|
const calls = new Map(), data = [], guard = new ToolArgumentDeltaGuard();let done = false, finish = null, usage = null, bytes = 0, visible = false;
|
|
184
185
|
const frame = async function* () {
|
|
@@ -188,6 +189,7 @@ export async function* chatStreamToAntigravity(response, originalNames, { onChun
|
|
|
188
189
|
let event;try { event = JSON.parse(raw); } catch { throw invalid("Invalid upstream Chat stream event", 502); }
|
|
189
190
|
const upstreamError = upstreamChatStreamError(event);if (upstreamError) throw upstreamError;
|
|
190
191
|
if (event?.usage) usage = event.usage;
|
|
192
|
+
if (event?.usage || event?.copilot_usage) onUsage?.(event);
|
|
191
193
|
const choice = event?.choices?.[0];
|
|
192
194
|
if (!choice) return;
|
|
193
195
|
if (choice.finish_reason) finish = choice.finish_reason;
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import {randomUUID} from "node:crypto";
|
|
2
|
+
import {buildResponsesUsageRecord,recordUsage} from "./usage-store.mjs";
|
|
2
3
|
import {createRequestAbort,readJsonBody,readBoundedResponseText,writeOrDrain,httpError,sendJsonError} from "./http-transport.mjs";
|
|
3
4
|
import {safeUpstreamResponseHeaders} from "./upstream-headers.mjs";
|
|
4
5
|
import {isLoopbackAddress,isLoopbackHostHeader} from "./security.mjs";
|
|
5
6
|
import {antigravityToChat,chatToAntigravity,chatStreamToAntigravity,parseAntigravityJSON} from "./antigravity-chat-bridge.mjs";
|
|
6
7
|
import {ANTIGRAVITY_MODEL_PREFIX,antigravityCopilotModels,mergeAntigravityModels} from "./antigravity-models.mjs";
|
|
7
8
|
import {createPrivacyTextFragments} from "./privacy-stream.mjs";
|
|
9
|
+
import {createGoogleResponseObserver,googleUsageEvent} from "./antigravity-usage.mjs";
|
|
8
10
|
import {currentRequestContext,observeRequestedModel} from "./request-context.mjs";
|
|
9
|
-
import {markUpstreamStarted,markUpstreamHeaders,markFirstOutput,markResponseTerminal} from "./stream-performance.mjs";
|
|
11
|
+
import {markUpstreamStarted,markUpstreamHeaders,markFirstOutput,markOutputTokens,markRequestObservation,markResponseModel,markResponseTerminal} from "./stream-performance.mjs";
|
|
10
12
|
|
|
11
13
|
const PREFIX="/antigravity";
|
|
12
14
|
const MAX_REPLY=64*1024*1024;
|
|
@@ -31,12 +33,26 @@ function groundedSearch(result,query){
|
|
|
31
33
|
}
|
|
32
34
|
|
|
33
35
|
export function createAntigravityHandler({client,models=()=>[],selectedModels=()=>null,enabled=()=>false,privacy,searchFn,imageFn,guardSource,acquireRequest=async()=>()=>{},
|
|
34
|
-
fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,streamIdleTimeoutMs=60000}={}) {
|
|
36
|
+
recordUsageFn=recordUsage,fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,streamIdleTimeoutMs=60000}={}) {
|
|
35
37
|
if(![GOOGLE_ORIGIN,"https://cloudcode-pa.googleapis.com"].includes(googleOrigin))throw new Error("Unrecognized Google control origin");
|
|
36
|
-
let active=0,observed=false;
|
|
38
|
+
let active=0,observed=false,catalogModels=null;
|
|
37
39
|
const counts={total:0,google:0,copilot:0,search:0,images:0,failed:0};
|
|
38
40
|
const handler=async(req,res)=>{
|
|
39
|
-
const abort=createRequestAbort(req,res);let release=()=>{},session;
|
|
41
|
+
const abort=createRequestAbort(req,res);let release=()=>{},session,usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
|
|
42
|
+
const captureUsage=event=>{
|
|
43
|
+
if(!event?.usage&&!event?.copilot_usage)return;
|
|
44
|
+
const known=value=>Number.isSafeInteger(value)&&value>=0,u={...usageEvent?.usage},incoming=event.usage;
|
|
45
|
+
for(const key of ["prompt_tokens","completion_tokens","total_tokens"])if(known(incoming?.[key]))u[key]=incoming[key];
|
|
46
|
+
for(const [key,field]of [["prompt_tokens_details","cached_tokens"],["completion_tokens_details","reasoning_tokens"]])if(known(incoming?.[key]?.[field]))u[key]={[field]:incoming[key][field]};
|
|
47
|
+
const billing=Array.isArray(event.copilot_usage?.token_details)?event.copilot_usage:undefined;
|
|
48
|
+
usageEvent={...usageEvent,...(Object.keys(u).length?{usage:u}:{}),...(billing?{copilot_usage:billing}:{}),
|
|
49
|
+
...(typeof event.id==="string"?{id:event.id}:{}),...(typeof event.model==="string"?{model:event.model}:{})};
|
|
50
|
+
markOutputTokens(u.completion_tokens);
|
|
51
|
+
if(typeof event.model==="string")markResponseModel(event.model);
|
|
52
|
+
const hasBilling=usageEvent.copilot_usage?.token_details.some(item=>known(item?.token_count)&&item.token_count>0);
|
|
53
|
+
markRequestObservation({input_tokens:u.prompt_tokens,cached_input_tokens:u.prompt_tokens_details?.cached_tokens,
|
|
54
|
+
usage_state:known(u.prompt_tokens)&&known(u.completion_tokens)&&known(u.prompt_tokens_details?.cached_tokens)?"reported":Object.keys(u).length||hasBilling?"partial":"missing"});
|
|
55
|
+
};
|
|
40
56
|
active++;counts.total++;
|
|
41
57
|
try{
|
|
42
58
|
if(!enabled())throw httpError("Antigravity integration is disabled",503);
|
|
@@ -51,21 +67,45 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
51
67
|
const body=req.method==="POST"?await readJsonBody(req,{admission:release,signal:abort.signal,parse:parseBody}):null;
|
|
52
68
|
const context=currentRequestContext();if(context)context.application="gemini_app";
|
|
53
69
|
if(body?.model)observeRequestedModel(body);
|
|
70
|
+
markRequestObservation({requested_model:context?.requestedModel});
|
|
54
71
|
abort.setTimeout(upstreamTimeoutMs,"upstream_timeout");
|
|
55
72
|
const generation=["streamGenerateContent","generateContent"].includes(method);
|
|
56
73
|
const native=async()=>{
|
|
57
74
|
counts.google++;
|
|
58
|
-
if(generation)
|
|
75
|
+
if(generation){
|
|
76
|
+
usageModel=body.model;usageProvider="google";usageMode=method==="streamGenerateContent"?"sse":"json";
|
|
77
|
+
if(context){context.provider="google";context.streamPerformance?.setProvider?.("google")}
|
|
78
|
+
markRequestObservation({usage_state:"pending"});markUpstreamStarted(method==="streamGenerateContent");
|
|
79
|
+
}
|
|
59
80
|
const upstream=await fetchGoogle(googleOrigin+route+local.search,{method:req.method,headers:{...nativeHeaders(req),...(body?{"content-type":"application/json"}:{})},
|
|
60
81
|
...(body?{body:JSON.stringify(body)}:{}),signal:abort.signal,redirect:"error"});
|
|
61
82
|
if(generation)markUpstreamHeaders(upstream.status);
|
|
62
83
|
if(method==="fetchAvailableModels"&&upstream.ok){
|
|
63
84
|
const value=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:8*1024*1024,signal:abort.signal,label:"Google model catalog"}));
|
|
64
85
|
const merged=mergeAntigravityModels(value,models(),selectedModels());
|
|
86
|
+
catalogModels=Object.keys(merged.models).filter(id=>id.startsWith(ANTIGRAVITY_MODEL_PREFIX));
|
|
65
87
|
res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"});res.end(JSON.stringify(merged));return;
|
|
66
88
|
}
|
|
89
|
+
const nativeStreaming=/text\/event-stream/i.test(upstream.headers.get("content-type")||"");
|
|
90
|
+
if(generation)usageMode=nativeStreaming?"sse":"json";
|
|
91
|
+
const observer=generation&&upstream.ok?createGoogleResponseObserver({streaming:nativeStreaming,onEvent:value=>{
|
|
92
|
+
const response=value?.response||value,event=googleUsageEvent(value);if(event)captureUsage(event);
|
|
93
|
+
const candidates=response?.candidates||[];
|
|
94
|
+
if(candidates.some(candidate=>candidate.content?.parts?.some(part=>part.functionCall||!part.thought&&typeof part.text==="string"&&part.text)))markFirstOutput("delta");
|
|
95
|
+
if(response?.error)outcome="failed";
|
|
96
|
+
else if(outcome!=="failed"&&candidates.some(candidate=>candidate.finishReason)){
|
|
97
|
+
outcome=candidates.every(candidate=>candidate.finishReason==="STOP")?"completed":"incomplete";
|
|
98
|
+
}
|
|
99
|
+
}}):null;
|
|
67
100
|
res.writeHead(upstream.status,safeUpstreamResponseHeaders(upstream.headers));
|
|
68
|
-
|
|
101
|
+
try{
|
|
102
|
+
if(upstream.body)for await(const data of upstream.body){
|
|
103
|
+
abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout");observer?.push(data);
|
|
104
|
+
if(!await writeOrDrain(res,data,{signal:abort.signal}))throw httpError("Antigravity client disconnected",499);
|
|
105
|
+
}
|
|
106
|
+
}finally{if(observer?.finish().unavailable&&!usageEvent)markRequestObservation({usage_state:"unavailable"})}
|
|
107
|
+
if(generation&&!upstream.ok)outcome="failed";
|
|
108
|
+
if(outcome)markResponseTerminal(outcome);
|
|
69
109
|
res.end();
|
|
70
110
|
};
|
|
71
111
|
if(!generation){
|
|
@@ -104,38 +144,54 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
104
144
|
if(!["agent","checkpoint","summarization","title"].includes(body.requestType))throw httpError("Unsupported Antigravity inference type",400);
|
|
105
145
|
const target=body.requestType==="agent"?selected:copilotModels.find(model=>model.model==="gemini-4-carbon"&&model.effort==="low");
|
|
106
146
|
if(!target)throw httpError("Copilot Carbon is unavailable for Antigravity background tasks",503);
|
|
107
|
-
const stream=method==="streamGenerateContent";
|
|
147
|
+
const stream=method==="streamGenerateContent";usageModel=target.model;usageMode=stream?"sse":"json";usageProvider="github";
|
|
108
148
|
const converted=antigravityToChat(request,{model:target.model,effort:target.effort,stream});
|
|
109
|
-
|
|
149
|
+
markResponseModel(target.model);markRequestObservation({usage_state:"pending"});
|
|
110
150
|
session=privacy?.prepareSession?await privacy.prepareSession(converted.chat,{protocol:"chat",client:"gemini",signal:abort.signal}):passthrough(converted.chat);
|
|
111
151
|
const upstream=await client.chatCompletions(session.body,{signal:abort.signal,retryOptions:{retries:0}});
|
|
152
|
+
markUpstreamHeaders(upstream.status);
|
|
112
153
|
if(!upstream.ok){await upstream.body?.cancel();throw httpError("Copilot generation was refused (HTTP "+upstream.status+")",upstream.status)}
|
|
113
154
|
if(!stream){
|
|
114
|
-
const
|
|
115
|
-
|
|
155
|
+
const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));captureUsage(data);
|
|
156
|
+
const result=chatToAntigravity(data,converted.originalNames);
|
|
157
|
+
outcome=result.candidates[0].finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome);
|
|
116
158
|
res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response:session.restoreValue(result)}));return;
|
|
117
159
|
}
|
|
118
160
|
const text=session.count?createPrivacyTextFragments(session):{push:value=>value,finish:()=>""};
|
|
119
161
|
res.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache"});
|
|
120
162
|
const emit=chunk=>writeOrDrain(res,"data: "+JSON.stringify(chunk)+"\n\n",{signal:abort.signal});
|
|
121
|
-
for await(const chunk of chatStreamToAntigravity(upstream,converted.originalNames,{onChunk:()=>abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout")})){
|
|
163
|
+
for await(const chunk of chatStreamToAntigravity(upstream,converted.originalNames,{onChunk:()=>abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout"),onUsage:captureUsage})){
|
|
122
164
|
const candidate=chunk.response?.candidates?.[0];
|
|
123
165
|
for(const part of candidate?.content?.parts||[]){
|
|
124
166
|
if(part.functionCall||typeof part.text==="string"&&part.text&&!part.thought)markFirstOutput("delta");
|
|
125
167
|
if(part.functionCall){const tail=text.finish();if(tail)await emit({response:{candidates:[{index:0,content:{role:"model",parts:[{text:tail}]}}]}});Object.assign(part,session.restoreToolValue(part));}
|
|
126
168
|
else if(typeof part.text==="string"&&!part.thought)part.text=text.push(part.text);
|
|
127
169
|
}
|
|
128
|
-
if(candidate?.finishReason){const tail=text.finish();if(tail)await emit({response:{candidates:[{index:0,content:{role:"model",parts:[{text:tail}]}}]}});
|
|
170
|
+
if(candidate?.finishReason){const tail=text.finish();if(tail)await emit({response:{candidates:[{index:0,content:{role:"model",parts:[{text:tail}]}}]}});outcome=candidate.finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome)}
|
|
129
171
|
await emit(chunk);
|
|
130
172
|
}
|
|
131
173
|
res.end();
|
|
132
174
|
}catch(error){
|
|
133
175
|
counts.failed++;
|
|
134
|
-
|
|
176
|
+
outcome=abort.signal.aborted&&["client_closed","client_aborted"].includes(abort.reason)?"cancelled":"failed";markResponseTerminal(outcome);
|
|
135
177
|
if(res.headersSent&&!res.writableEnded&&!res.destroyed){res.end("data: "+JSON.stringify({error:{code:error.statusCode||502,message:error.message}})+"\n\n");}
|
|
136
178
|
else sendJsonError(res,error,error.statusCode||502);
|
|
137
|
-
}finally{
|
|
179
|
+
}finally{
|
|
180
|
+
session?.release();release();abort.cleanup();active--;
|
|
181
|
+
if(usageEvent){
|
|
182
|
+
const u=usageEvent.usage,record=buildResponsesUsageRecord({surface:"antigravity",mode:usageMode,model:usageModel,
|
|
183
|
+
response:{id:usageEvent.id,model:usageEvent.model||usageModel,usage:u?{input_tokens:u.prompt_tokens,output_tokens:u.completion_tokens,
|
|
184
|
+
total_tokens:u.total_tokens,input_tokens_details:u.prompt_tokens_details,output_tokens_details:u.completion_tokens_details}:undefined},
|
|
185
|
+
event:{copilot_usage:usageEvent.copilot_usage}});
|
|
186
|
+
if(record){
|
|
187
|
+
markRequestObservation({input_tokens:record.usage?.input_tokens,cached_input_tokens:record.usage?.cached_input_tokens});
|
|
188
|
+
const context=currentRequestContext();
|
|
189
|
+
recordUsageFn({...record,provider:usageProvider,client:"gemini",request_id:context?.requestId,requested_model:context?.requestedModel,
|
|
190
|
+
outcome:outcome||"unknown",...(outcome!=="completed"?{partial:true}:{})});
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
138
194
|
};
|
|
139
|
-
handler.snapshot=()=>({enabled:enabled(),observed,active,...counts});
|
|
195
|
+
handler.snapshot=()=>({enabled:enabled(),observed,catalog_models:catalogModels,active,...counts});
|
|
140
196
|
return handler;
|
|
141
197
|
}
|
|
@@ -41,10 +41,18 @@ export function createAntigravityRuntime({client,models=()=>[],privacy,home=os.h
|
|
|
41
41
|
const handler=createAntigravityHandler({client,models:available,selectedModels:()=>settings().selected_models,enabled:()=>settings().configured,privacy,searchFn:searchFn||web.search,
|
|
42
42
|
imageFn:imageFn||createAntigravityImages({client,models:available,privacy}),guardSource:sourceGuard,fetchGoogle:googleFetch,acquireRequest,...timeouts});
|
|
43
43
|
function snapshot(){
|
|
44
|
-
const config=settings();
|
|
45
|
-
|
|
44
|
+
const config=settings(),sourceEnabled=readAccessSettings(options).providers.github,activity=handler.snapshot();
|
|
45
|
+
const listed=antigravityCopilotModels(models()).map(({id,model,displayName,effort,maxTokens})=>({id,model,name:displayName,effort,context_window:maxTokens,selected:config.selected_models===null||config.selected_models.includes(id)}));
|
|
46
|
+
const groups=new Map();
|
|
47
|
+
for(const variant of listed){
|
|
48
|
+
if(!groups.has(variant.model))groups.set(variant.model,{id:variant.model,name:variant.name.split(" · Copilot")[0],source:"github",context_window:variant.context_window,efforts:[]});
|
|
49
|
+
groups.get(variant.model).efforts.push({id:variant.id,effort:variant.effort,selected:variant.selected});
|
|
50
|
+
}
|
|
51
|
+
const expected=listed.filter(model=>model.selected).map(model=>model.id).sort();
|
|
52
|
+
const reload=config.enabled&&sourceEnabled?(activity.catalog_models===null?null:JSON.stringify([...activity.catalog_models].sort())!==JSON.stringify(expected)):false;
|
|
53
|
+
return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,models_reload_required:reload,app,route_observed:handler.snapshot().observed,
|
|
46
54
|
model_source:"Google + GitHub Copilot",background_source:"GitHub Copilot",ordinary_chat_source:"Google (unchanged)",
|
|
47
|
-
models:
|
|
55
|
+
models:listed,model_groups:[...groups.values()],activity,last_operation:lastOperation};
|
|
48
56
|
}
|
|
49
57
|
async function action(input={},baseUrl){
|
|
50
58
|
if(input&&Object.keys(input).some(name=>!["action","accept_background_copilot","models"].includes(name)))throw httpError("Invalid Gemini operation",400);
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { loadRuntimeConfig } from "./runtime-config.mjs";
|
|
2
|
+
|
|
3
|
+
const MAX_BYTES = loadRuntimeConfig().maxSseBufferBytes;
|
|
4
|
+
const count = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
5
|
+
|
|
6
|
+
export function googleUsageEvent(value) {
|
|
7
|
+
const response = value?.response || value, usage = response?.usageMetadata;
|
|
8
|
+
if (!usage || typeof usage !== "object") return null;
|
|
9
|
+
const prompt = count(usage.promptTokenCount), output = count(usage.candidatesTokenCount);
|
|
10
|
+
const thoughts = count(usage.thoughtsTokenCount), tools = count(usage.toolUsePromptTokenCount);
|
|
11
|
+
return {
|
|
12
|
+
id: response.responseId, model: response.modelVersion,
|
|
13
|
+
usage: {
|
|
14
|
+
prompt_tokens: prompt === undefined ? undefined : prompt + (tools ?? 0),
|
|
15
|
+
completion_tokens: output === undefined ? undefined : output + (thoughts ?? 0),
|
|
16
|
+
total_tokens: count(usage.totalTokenCount),
|
|
17
|
+
prompt_tokens_details: { cached_tokens: count(usage.cachedContentTokenCount) },
|
|
18
|
+
completion_tokens_details: { reasoning_tokens: thoughts },
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Observe the same chunks the caller forwards, without buffering delivery,
|
|
24
|
+
// changing bytes or reading ahead. Oversized metadata is unavailable, not zero.
|
|
25
|
+
export function createGoogleResponseObserver({ streaming, onEvent, maxBytes = MAX_BYTES }) {
|
|
26
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
27
|
+
let parts = [], bytes = 0, data = [], frameBytes = 0, skipLF = false, skipFrame = false, unavailable = false;
|
|
28
|
+
const parse = text => {
|
|
29
|
+
if (!text || text === "[DONE]") return;
|
|
30
|
+
try { const value = JSON.parse(text);for (const item of Array.isArray(value) ? value : [value]) onEvent(item); }
|
|
31
|
+
catch { unavailable = true; }
|
|
32
|
+
};
|
|
33
|
+
const line = () => {
|
|
34
|
+
const text = parts.join("");parts = [];bytes = 0;
|
|
35
|
+
if (!text) {
|
|
36
|
+
if (!skipFrame) parse(data.join("\n"));
|
|
37
|
+
data = [];frameBytes = 0;skipFrame = false;
|
|
38
|
+
} else if (!skipFrame && text.startsWith("data:")) {
|
|
39
|
+
const value = text.slice(5).replace(/^ /, "");frameBytes += Buffer.byteLength(value);
|
|
40
|
+
if (frameBytes > maxBytes) { data = [];skipFrame = true;unavailable = true; }
|
|
41
|
+
else data.push(value);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
const consume = text => {
|
|
45
|
+
if (!streaming) {
|
|
46
|
+
if (unavailable) return;
|
|
47
|
+
bytes += Buffer.byteLength(text);
|
|
48
|
+
if (bytes > maxBytes) { parts = [];unavailable = true; } else parts.push(text);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
let start = 0;
|
|
52
|
+
if (skipLF && text.length) { if (text[0] === "\n") start = 1;skipLF = false; }
|
|
53
|
+
const newline = /[\r\n]/g;newline.lastIndex = start;let match;
|
|
54
|
+
const append = fragment => {
|
|
55
|
+
if (skipFrame) return;
|
|
56
|
+
bytes += Buffer.byteLength(fragment);
|
|
57
|
+
if (bytes > maxBytes) { parts = [];data = [];skipFrame = true;unavailable = true; }
|
|
58
|
+
else parts.push(fragment);
|
|
59
|
+
};
|
|
60
|
+
while ((match = newline.exec(text))) {
|
|
61
|
+
const hadLine = bytes > 0 || parts.length > 0 || skipFrame && match.index > start;
|
|
62
|
+
append(text.slice(start, match.index));
|
|
63
|
+
if (skipFrame && (hadLine || match.index > start)) { parts = [];bytes = 0; }
|
|
64
|
+
else line();
|
|
65
|
+
start = match.index + 1;
|
|
66
|
+
if (match[0] === "\r") {
|
|
67
|
+
if (text[start] === "\n") start++;
|
|
68
|
+
else if (start === text.length) skipLF = true;
|
|
69
|
+
newline.lastIndex = start;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
append(text.slice(start));
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
push(chunk) { try { consume(decoder.decode(chunk, { stream: true })); } catch { unavailable = true;parts = [];data = []; } },
|
|
76
|
+
finish() {
|
|
77
|
+
try {
|
|
78
|
+
consume(decoder.decode());
|
|
79
|
+
if (streaming) { if (parts.length) line();if (!skipFrame && data.length) parse(data.join("\n")); }
|
|
80
|
+
else if (!unavailable) parse(parts.join(""));
|
|
81
|
+
} catch { unavailable = true; }
|
|
82
|
+
parts = [];data = [];
|
|
83
|
+
return { unavailable };
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|