codex-copilot-dx 1.3.25 → 1.3.27
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 +2 -2
- package/bin/cli.mjs +2 -2
- package/docs/ARCHITECTURE.md +6 -0
- package/docs/REFERENCE.md +24 -3
- package/package.json +1 -1
- package/src/antigravity-chat-bridge.mjs +2 -1
- package/src/antigravity-handler.mjs +67 -13
- package/src/antigravity-runtime.mjs +7 -2
- package/src/antigravity-usage.mjs +86 -0
- package/src/cli-command-spec.mjs +9 -4
- package/src/cli-management.mjs +25 -5
- package/src/client-versions.mjs +17 -13
- package/src/dashboard/console.js +1 -1
- package/src/dashboard/context.js +8 -4
- package/src/dashboard/flow.js +12 -11
- package/src/dashboard/gemini.js +20 -5
- package/src/dashboard/index.html +10 -9
- package/src/dashboard/language.js +31 -9
- package/src/dashboard/status.js +11 -2
- package/src/dashboard/ui.js +18 -7
- package/src/dashboard/usage.js +35 -19
- package/src/dashboard-api.mjs +19 -6
- 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 supported reasoning levels shown in the same format as Codex and Claude. 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
|
|
|
@@ -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/bin/cli.mjs
CHANGED
|
@@ -329,9 +329,9 @@ const clientVersions = {
|
|
|
329
329
|
snapshot: () => versionMonitor?.snapshot() || null,
|
|
330
330
|
refresh() {
|
|
331
331
|
if (shuttingDown || serviceWorker?.warming || serviceWorker?.draining || serviceWorker?.preserving) return Promise.resolve(clientVersions.snapshot());
|
|
332
|
-
versionModule ||= import("../src/client-versions.mjs").then(({ createClientVersionMonitor }) => {
|
|
332
|
+
versionModule ||= import("../src/client-versions.mjs").then(({ createClientVersionMonitor, clientVersionName }) => {
|
|
333
333
|
if (shuttingDown) return null;
|
|
334
|
-
versionMonitor = createClientVersionMonitor({ onChange: names => console.log(status("info", `Installed ${names.map(
|
|
334
|
+
versionMonitor = createClientVersionMonitor({ onChange: names => console.log(status("info", `Installed ${names.map(clientVersionName).join(" and ")} updated; check integration in the WebUI or ccdx doctor`)) });
|
|
335
335
|
return versionMonitor;
|
|
336
336
|
}).catch(error => { versionModule = null;throw error; });
|
|
337
337
|
return versionModule.then(monitor => monitor?.refresh());
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -17,6 +17,10 @@ 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 groups selection by model and renders supported effort levels as read-only capability text, matching the Codex/Claude tables. Existing route subsets survive a model off/on toggle; CLI effort editing and JSON aliases remain compatible.
|
|
23
|
+
|
|
20
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.
|
|
21
25
|
|
|
22
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.
|
|
@@ -553,6 +557,8 @@ projects the optional lightweight response; full status stays the default public
|
|
|
553
557
|
contract. Hidden status regions defer DOM updates, and summary rendering never
|
|
554
558
|
replaces the full request/history cache.
|
|
555
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
|
+
|
|
556
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.
|
|
557
563
|
|
|
558
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.
|
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,7 +68,9 @@ 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`.
|
|
71
|
+
`app antigravity models --edit`. Each WebUI row represents one model. The Reasoning column lists supported levels as `low / medium / high`, matching Codex and Claude; the model checkbox controls visibility. Save/Discard, refresh, navigation, pausing and an off/on toggle preserve an existing saved route subset. CLI model editing and model files remain available for fine-grained effort selection.
|
|
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.
|
|
72
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.
|
|
73
75
|
|
|
74
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.
|
|
@@ -152,11 +154,30 @@ Catalog diagnostics distinguish local cached data from an online response and ex
|
|
|
152
154
|
- **Request failure:** use Requests or `ccdx requests --failed`. HTTP failures and model completion outcomes are separate. A successful HTTP transport can still carry a model error.
|
|
153
155
|
- **Token counting unavailable:** an observed API count-endpoint 404 is cached briefly per model/header scope. Inference and token counting are separate capabilities; no synthetic count is returned.
|
|
154
156
|
- **Local checks:** `doctor` is read-only by default. `--online` checks access; `--compat` sends minimal inference and consumes usage. `--fix` backs up owned configuration and performs bounded repairs. It does not enable optional features, change company policy or force-restart apps. Partial repairs exit 1.
|
|
155
|
-
- **App updates:** after the service is ready, CCDX observes installed App versions in the background. Checks & repairs shows the result; `ccdx doctor` can inspect it locally. On macOS this uses known App bundle metadata and, when available, the bundled Codex CLI version. On Windows the registered Codex package is inspected; Claude App remains unknown if reliable metadata is unavailable. The running process may still be an older build, and a version observation does not verify images, predictions, model access or protocol compatibility. A detected unrecognized Claude App major version preserves existing shared capability fields during later synchronization. The compact local version record contains only App versions, builds and observation times, not credentials or conversation data. It is refreshed on startup, local checks and the existing model-refresh cadence; a reused service receives a nonblocking refresh notification.
|
|
157
|
+
- **App updates:** after the service is ready, CCDX observes installed App versions in the background. Checks & repairs shows the result; `ccdx doctor` can inspect it locally. On macOS this includes Antigravity (the original Gemini App) and uses known App bundle metadata and, when available, the bundled Codex CLI version. On Windows the registered Codex package is inspected; Claude App remains unknown if reliable metadata is unavailable. The running process may still be an older build, and a version observation does not verify images, predictions, model access or protocol compatibility. A detected unrecognized Claude App major version preserves existing shared capability fields during later synchronization. The compact local version record contains only App versions, builds and observation times, not credentials or conversation data. It is refreshed on startup, local checks and the existing model-refresh cadence; a reused service receives a nonblocking refresh notification.
|
|
156
158
|
- **Cache cleanup:** adding `--history` can break the next continuation. It does not delete client transcripts or generated images.
|
|
157
159
|
|
|
158
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.
|
|
159
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
|
+
|
|
160
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.
|
|
161
182
|
|
|
162
183
|
## Settings and appearance
|
package/package.json
CHANGED
|
@@ -179,7 +179,7 @@ export function chatToAntigravity(response, originalNames) {
|
|
|
179
179
|
...(usage ? { usageMetadata: { promptTokenCount: usage.prompt_tokens || 0, candidatesTokenCount: usage.completion_tokens || 0, totalTokenCount: usage.total_tokens || 0 } } : {}) };
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
-
export async function* chatStreamToAntigravity(response, originalNames, { onChunk } = {}) {
|
|
182
|
+
export async function* chatStreamToAntigravity(response, originalNames, { onChunk, onUsage } = {}) {
|
|
183
183
|
if (!response?.body) throw invalid("Upstream Chat stream has no body", 502);
|
|
184
184
|
const calls = new Map(), data = [], guard = new ToolArgumentDeltaGuard();let done = false, finish = null, usage = null, bytes = 0, visible = false;
|
|
185
185
|
const frame = async function* () {
|
|
@@ -189,6 +189,7 @@ export async function* chatStreamToAntigravity(response, originalNames, { onChun
|
|
|
189
189
|
let event;try { event = JSON.parse(raw); } catch { throw invalid("Invalid upstream Chat stream event", 502); }
|
|
190
190
|
const upstreamError = upstreamChatStreamError(event);if (upstreamError) throw upstreamError;
|
|
191
191
|
if (event?.usage) usage = event.usage;
|
|
192
|
+
if (event?.usage || event?.copilot_usage) onUsage?.(event);
|
|
192
193
|
const choice = event?.choices?.[0];
|
|
193
194
|
if (!choice) return;
|
|
194
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
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,11 +67,16 @@ 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);
|
|
@@ -65,8 +86,26 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
65
86
|
catalogModels=Object.keys(merged.models).filter(id=>id.startsWith(ANTIGRAVITY_MODEL_PREFIX));
|
|
66
87
|
res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"});res.end(JSON.stringify(merged));return;
|
|
67
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;
|
|
68
100
|
res.writeHead(upstream.status,safeUpstreamResponseHeaders(upstream.headers));
|
|
69
|
-
|
|
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);
|
|
70
109
|
res.end();
|
|
71
110
|
};
|
|
72
111
|
if(!generation){
|
|
@@ -105,38 +144,53 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
105
144
|
if(!["agent","checkpoint","summarization","title"].includes(body.requestType))throw httpError("Unsupported Antigravity inference type",400);
|
|
106
145
|
const target=body.requestType==="agent"?selected:copilotModels.find(model=>model.model==="gemini-4-carbon"&&model.effort==="low");
|
|
107
146
|
if(!target)throw httpError("Copilot Carbon is unavailable for Antigravity background tasks",503);
|
|
108
|
-
const stream=method==="streamGenerateContent";
|
|
147
|
+
const stream=method==="streamGenerateContent";usageModel=target.model;usageMode=stream?"sse":"json";usageProvider="github";
|
|
109
148
|
const converted=antigravityToChat(request,{model:target.model,effort:target.effort,stream});
|
|
110
|
-
|
|
149
|
+
markResponseModel(target.model);markRequestObservation({usage_state:"pending"});
|
|
111
150
|
session=privacy?.prepareSession?await privacy.prepareSession(converted.chat,{protocol:"chat",client:"gemini",signal:abort.signal}):passthrough(converted.chat);
|
|
112
151
|
const upstream=await client.chatCompletions(session.body,{signal:abort.signal,retryOptions:{retries:0}});
|
|
113
152
|
markUpstreamHeaders(upstream.status);
|
|
114
153
|
if(!upstream.ok){await upstream.body?.cancel();throw httpError("Copilot generation was refused (HTTP "+upstream.status+")",upstream.status)}
|
|
115
154
|
if(!stream){
|
|
116
|
-
const
|
|
117
|
-
|
|
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);
|
|
118
158
|
res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response:session.restoreValue(result)}));return;
|
|
119
159
|
}
|
|
120
160
|
const text=session.count?createPrivacyTextFragments(session):{push:value=>value,finish:()=>""};
|
|
121
161
|
res.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache"});
|
|
122
162
|
const emit=chunk=>writeOrDrain(res,"data: "+JSON.stringify(chunk)+"\n\n",{signal:abort.signal});
|
|
123
|
-
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})){
|
|
124
164
|
const candidate=chunk.response?.candidates?.[0];
|
|
125
165
|
for(const part of candidate?.content?.parts||[]){
|
|
126
166
|
if(part.functionCall||typeof part.text==="string"&&part.text&&!part.thought)markFirstOutput("delta");
|
|
127
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));}
|
|
128
168
|
else if(typeof part.text==="string"&&!part.thought)part.text=text.push(part.text);
|
|
129
169
|
}
|
|
130
|
-
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)}
|
|
131
171
|
await emit(chunk);
|
|
132
172
|
}
|
|
133
173
|
res.end();
|
|
134
174
|
}catch(error){
|
|
135
175
|
counts.failed++;
|
|
136
|
-
|
|
176
|
+
outcome=abort.signal.aborted&&["client_closed","client_aborted"].includes(abort.reason)?"cancelled":"failed";markResponseTerminal(outcome);
|
|
137
177
|
if(res.headersSent&&!res.writableEnded&&!res.destroyed){res.end("data: "+JSON.stringify({error:{code:error.statusCode||502,message:error.message}})+"\n\n");}
|
|
138
178
|
else sendJsonError(res,error,error.statusCode||502);
|
|
139
|
-
}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
|
+
}
|
|
140
194
|
};
|
|
141
195
|
handler.snapshot=()=>({enabled:enabled(),observed,catalog_models:catalogModels,active,...counts});
|
|
142
196
|
return handler;
|
|
@@ -42,12 +42,17 @@ export function createAntigravityRuntime({client,models=()=>[],privacy,home=os.h
|
|
|
42
42
|
imageFn:imageFn||createAntigravityImages({client,models:available,privacy}),guardSource:sourceGuard,fetchGoogle:googleFetch,acquireRequest,...timeouts});
|
|
43
43
|
function snapshot(){
|
|
44
44
|
const config=settings(),sourceEnabled=readAccessSettings(options).providers.github,activity=handler.snapshot();
|
|
45
|
-
const listed=antigravityCopilotModels(models()).map(({id,displayName,effort,maxTokens})=>({id,name:displayName,effort,context_window:maxTokens,selected:config.selected_models===null||config.selected_models.includes(id)}));
|
|
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
|
+
}
|
|
46
51
|
const expected=listed.filter(model=>model.selected).map(model=>model.id).sort();
|
|
47
52
|
const reload=config.enabled&&sourceEnabled?(activity.catalog_models===null?null:JSON.stringify([...activity.catalog_models].sort())!==JSON.stringify(expected)):false;
|
|
48
53
|
return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,models_reload_required:reload,app,route_observed:handler.snapshot().observed,
|
|
49
54
|
model_source:"Google + GitHub Copilot",background_source:"GitHub Copilot",ordinary_chat_source:"Google (unchanged)",
|
|
50
|
-
models:listed,activity,last_operation:lastOperation};
|
|
55
|
+
models:listed,model_groups:[...groups.values()],activity,last_operation:lastOperation};
|
|
51
56
|
}
|
|
52
57
|
async function action(input={},baseUrl){
|
|
53
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
|
+
}
|
package/src/cli-command-spec.mjs
CHANGED
|
@@ -184,6 +184,11 @@ export const MANAGED_COMMANDS = [
|
|
|
184
184
|
...read,
|
|
185
185
|
"--scope": "scope",
|
|
186
186
|
"--provider": "value",
|
|
187
|
+
"--model": "value",
|
|
188
|
+
"--days": "value",
|
|
189
|
+
"--from": "value",
|
|
190
|
+
"--to": "value",
|
|
191
|
+
"--time-zone": "value",
|
|
187
192
|
}),
|
|
188
193
|
command("update check", "Check a stable release without installing", read),
|
|
189
194
|
command("update apply", "Request the WebUI's verified idle service update", { "--yes": "flag" }, flags => ({ command: "update-managed", yes: !!flags.yes })),
|
|
@@ -225,8 +230,8 @@ function optionsFor(args, definition) {
|
|
|
225
230
|
throw new Error("Limit must be an integer from 1 to 100");
|
|
226
231
|
values[key] = type === "integer" ? Number(value) : value;
|
|
227
232
|
}
|
|
228
|
-
if (values.app && !Object.hasOwn(CLI_CLIENTS, values.app))
|
|
229
|
-
throw new Error("Choose codex, claude-app
|
|
233
|
+
if (values.app && !Object.hasOwn(CLI_CLIENTS, values.app) && !(definition.path[0] === "requests" && values.app === "antigravity"))
|
|
234
|
+
throw new Error("Choose codex, claude-app, claude-code or antigravity for requests");
|
|
230
235
|
if (values.provider && !isProviderId(values.provider)) throw new Error("Enter a valid usage source ID");
|
|
231
236
|
if (values.source && !isProviderId(values.source)) throw new Error("Enter a listed source ID");
|
|
232
237
|
if (values.active && values.failed) throw new Error("Choose --active or --failed");
|
|
@@ -276,11 +281,11 @@ const extras = {
|
|
|
276
281
|
config:
|
|
277
282
|
"Only service and terminal preferences are in scope. Browser appearance stays in WebUI.\nReset keeps accounts, keys, model plans and chats and stores a pre-reset backup.\nSaved and effective values can differ; restart requirements remain explicit.",
|
|
278
283
|
requests:
|
|
279
|
-
"Only retained records are available. Unknown clients are not guessed from an API route.\n--failed filters failed model outcomes and structured HTTP/model errors.\nUsage records, HTTP calls and model outcomes are distinct counters.",
|
|
284
|
+
"Only retained records are available. Unknown clients are not guessed from an API route.\nApp filters: codex, claude-app, claude-code, antigravity.\n--failed filters failed model outcomes and structured HTTP/model errors.\nUsage records, HTTP calls and model outcomes are distinct counters.",
|
|
280
285
|
status:
|
|
281
286
|
"Default interactive status is brief; --details retains the complete diagnostic view.\nThe installed package version can differ from the running service.\nA listening gateway does not prove upstream model access.",
|
|
282
287
|
usage:
|
|
283
|
-
"Default usage includes all recorded usage. --scope run reads the running service.\nUsage records are not billed request counts. Cache hit is a token-reuse estimate.",
|
|
288
|
+
"Default usage includes all recorded usage. Filter it with --provider, --model and --days 1..365|all, or --from/--to YYYY-MM-DD.\nDates use --time-zone (UTC by default). Source-qualified models use 'source / model'.\n--scope run reads the running service and supports only --provider.\nGemini usage includes Antigravity Copilot and native Google responses. Missing upstream counts stay unknown; historical missing usage is not reconstructed.\nUsage records are not billed request counts. Cache hit is a token-reuse estimate.",
|
|
284
289
|
doctor:
|
|
285
290
|
"Default checks are read-only. Explicit online/compatibility checks and owned repairs have separate options.",
|
|
286
291
|
update:
|
package/src/cli-management.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { createInterface } from "node:readline/promises";
|
|
|
3
3
|
import { dashboardToolRequest } from "./cli-tools.mjs";
|
|
4
4
|
import { readAdapterStatus } from "./cli-status.mjs";
|
|
5
5
|
import { CLI_CLIENTS } from "./cli-command-spec.mjs";
|
|
6
|
-
import { projectTerminalState, retainedRequests, clientSetup, TERMINAL_CLIENT_NAMES, terminalUptime } from "./terminal-state.mjs";
|
|
6
|
+
import { projectTerminalState, retainedRequests, clientSetup, TERMINAL_CLIENT_NAMES, terminalUptime, terminalRequestState } from "./terminal-state.mjs";
|
|
7
7
|
import { formatResponsiveCliTable, cliOutputWidth, terminalCell } from "./cli-table.mjs";
|
|
8
8
|
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
9
9
|
import { settingsPreferencesSnapshot, writeSettingsPreferences, checkedPreferenceValues } from "./settings-preferences.mjs";
|
|
@@ -115,17 +115,22 @@ export async function runManagementCommand(command, options = {}) {
|
|
|
115
115
|
const found = rows.find(row => row.request_id === ids.request);if (!found) throw new Error("Request not retained. No full-history lookup is available.");return print(found);
|
|
116
116
|
}
|
|
117
117
|
rows = rows.filter(row => (!flags.active || row.active) && (!flags.failed || row.state !== "cancelled" && (row.state === "failed" || row.error))
|
|
118
|
-
&& (!flags.source || row.provider === flags.source) && (!flags.app || (flags.app === "codex" ? ["codex", "codex_app", "codex_cli"].includes(row.application) : row.application === CLI_CLIENTS[flags.app]))).slice(-(flags.limit || 20));
|
|
119
|
-
return print(rows, [["request_id", "Request"], ["application", "Client"], ["provider", "Source"], ["model", "Model"], ["route", "Route"], ["
|
|
118
|
+
&& (!flags.source || row.provider === flags.source) && (!flags.app || (flags.app === "codex" ? ["codex", "codex_app", "codex_cli"].includes(row.application) : row.application === (flags.app === "antigravity" ? "gemini_app" : CLI_CLIENTS[flags.app])))).slice(-(flags.limit || 20));
|
|
119
|
+
return print(flags.format === "json" ? rows : rows.map(row => ({ ...row, state_label: terminalRequestState(row) })), [["request_id", "Request"], ["application", "Client"], ["provider", "Source"], ["model", "Model"], ["route", "Route"], ["state_label", "State"]]);
|
|
120
120
|
}
|
|
121
121
|
if (group === "usage") {
|
|
122
122
|
if (flags.scope === "run") {
|
|
123
|
+
if (flags.model || flags.days || flags.from || flags.to || flags.time_zone) throw new Error("Model and date filters require --scope all; current-run totals support only --provider.");
|
|
123
124
|
const usage = (await readStatus()).data.runtime_usage;
|
|
124
125
|
if (!usage) throw new Error("Current-run usage is unavailable.");
|
|
125
126
|
return print(flags.provider ? usage.by_provider?.[flags.provider] || { records: 0 } : usage);
|
|
126
127
|
}
|
|
127
128
|
const { summarizeUsageLogs } = await import("./usage-store.mjs");
|
|
128
|
-
const
|
|
129
|
+
const { createUsageQuery } = await import("./usage-query.mjs");
|
|
130
|
+
const selection = createUsageQuery({ provider: flags.provider, model: flags.model, days: flags.days, from: flags.from, to: flags.to, timeZone: flags.time_zone });
|
|
131
|
+
const filtered = selection.filters.model || selection.filters.from || selection.filters.to;
|
|
132
|
+
const summary = await summarizeUsageLogs(undefined, { ...(flags.provider ? { provider: flags.provider } : {}), ...(filtered ? { recordFilter: selection.matches } : {}) });
|
|
133
|
+
summary.filters = selection.filters;
|
|
129
134
|
if (flags.format === "json") return print(summary);
|
|
130
135
|
const { formatUsageSummary } = await import("./usage.mjs");
|
|
131
136
|
return formatUsageSummary(summary, { format: flags.format || "auto", output });
|
|
@@ -191,13 +196,28 @@ export async function runManagementCommand(command, options = {}) {
|
|
|
191
196
|
}
|
|
192
197
|
if(action==="models"&&flags.edit){
|
|
193
198
|
const state=await request({path:"gemini"});
|
|
194
|
-
|
|
199
|
+
let ids;
|
|
200
|
+
if(flags.file){
|
|
201
|
+
const listed=readFile().models;if(!Array.isArray(listed))throw new Error("Model files require a models array.");
|
|
202
|
+
ids=listed.flatMap(id=>state.model_groups?.find(model=>model.id===id)?.efforts.map(item=>item.id)||[id]);
|
|
203
|
+
}
|
|
204
|
+
else if(Array.isArray(state.model_groups)){
|
|
205
|
+
const groups=state.model_groups,selected=await choose(groups.map(model=>model.name),groups.flatMap((model,index)=>model.efforts.some(item=>item.selected)?[index]:[]));
|
|
206
|
+
ids=[];
|
|
207
|
+
for(const index of selected){
|
|
208
|
+
const model=groups[index],previous=model.efforts.flatMap((item,i)=>item.selected?[i]:[]);
|
|
209
|
+
const efforts=await choose(model.efforts.map(item=>model.name+" / "+item.effort),previous.length?previous:model.efforts.map((_,i)=>i));
|
|
210
|
+
ids.push(...efforts.map(i=>model.efforts[i].id));
|
|
211
|
+
}
|
|
212
|
+
}else ids=(await choose(state.models.map(model=>model.name),state.models.flatMap((model,index)=>model.selected!==false?[index]:[]))).map(index=>state.models[index].id);
|
|
195
213
|
if(!Array.isArray(ids)||new Set(ids).size!==ids.length||ids.some(id=>!state.models.some(model=>model.id===id)))throw new Error("Choose listed Antigravity model IDs.");
|
|
196
214
|
if(flags.preview)return print({models:ids,saved:false});
|
|
197
215
|
await confirm("Save Antigravity model selection? Reopen Gemini afterward to reload it.");
|
|
198
216
|
return print(await request({path:"gemini",body:{action:"models",models:ids}}));
|
|
199
217
|
}
|
|
200
218
|
const state = await request({ path: "gemini", ...(["status", "models"].includes(action) ? {} : { body: { action: flags.preview ? "preview" : action, ...(action === "enable" ? { accept_background_copilot: true } : {}) }, timeoutMs: 20000 }) });
|
|
219
|
+
if(action==="models"&&flags.format!=="json"&&state.model_groups)return print(state.model_groups.map(model=>({model:model.name,id:model.id,source:"GitHub Copilot",context:model.context_window,
|
|
220
|
+
efforts:model.efforts.map(item=>item.effort+(item.selected?" ✓":"")).join(" / ")})),[["model","Model"],["id","ID"],["source","Source"],["context","Context"],["efforts","Reasoning (selected ✓)"]]);
|
|
201
221
|
return print(action === "models" ? state.models : state);
|
|
202
222
|
}
|
|
203
223
|
const graph = await connection(), snapshot = (await readStatus()).data, view = projectTerminalState(snapshot);
|
package/src/client-versions.mjs
CHANGED
|
@@ -6,6 +6,10 @@ import { readBoundedFile } from "./bounded-file.mjs";
|
|
|
6
6
|
import { userSettingsPath } from "./user-settings.mjs";
|
|
7
7
|
|
|
8
8
|
const MAX_METADATA_BYTES = 64 * 1024;
|
|
9
|
+
const MAX_APPS = 9;
|
|
10
|
+
export const clientVersionName = client => ({ codex: "Codex App", claude: "Claude App", antigravity: "Antigravity" })[client] || client;
|
|
11
|
+
const validId = value => /^(?:codex|claude)_(?:system|user|windows)_(?:chatgpt|codex|claude)$/.test(value)
|
|
12
|
+
|| /^antigravity_(?:system|user)_gemini$/.test(value);
|
|
9
13
|
const validVersion = value => typeof value === "string" && /^[0-9][0-9A-Za-z.+_-]{0,63}$/.test(value);
|
|
10
14
|
const optionalVersion = value => value == null || validVersion(value);
|
|
11
15
|
const validDate = value => value == null || typeof value === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(value);
|
|
@@ -29,7 +33,7 @@ async function stableRead(file) {
|
|
|
29
33
|
|
|
30
34
|
async function macBundle(root, scope, name, client) {
|
|
31
35
|
const bundle = path.join(root, name), infoPath = path.join(bundle, "Contents", "Info.plist"), info = await stableRead(infoPath), plist = info.data;
|
|
32
|
-
const expected = client === "codex" ? "com.openai.codex" : "com.anthropic.claudefordesktop";
|
|
36
|
+
const expected = client === "codex" ? "com.openai.codex" : client === "claude" ? "com.anthropic.claudefordesktop" : "com.google.GeminiMacOS";
|
|
33
37
|
const version = tag(plist, "CFBundleShortVersionString"), build = tag(plist, "CFBundleVersion");
|
|
34
38
|
if (tag(plist, "CFBundleIdentifier") !== expected || !validVersion(version) || !optionalVersion(build)) return null;
|
|
35
39
|
let cliVersion = null;
|
|
@@ -45,7 +49,7 @@ export async function inspectInstalledClientVersions({ home = os.homedir(), env
|
|
|
45
49
|
systemApplications = "/Applications", windowsCodexVersion } = {}) {
|
|
46
50
|
if (platform === "darwin") {
|
|
47
51
|
const roots = [["system", systemApplications], ["user", path.join(home, "Applications")]], jobs = [];
|
|
48
|
-
for (const [scope, root] of roots) for (const [name, client] of [["ChatGPT.app", "codex"], ["Codex.app", "codex"], ["Claude.app", "claude"]]) {
|
|
52
|
+
for (const [scope, root] of roots) for (const [name, client] of [["ChatGPT.app", "codex"], ["Codex.app", "codex"], ["Claude.app", "claude"], ["Gemini.app", "antigravity"]]) {
|
|
49
53
|
jobs.push(macBundle(root, scope, name, client).catch(() => null));
|
|
50
54
|
}
|
|
51
55
|
return (await Promise.all(jobs)).filter(Boolean);
|
|
@@ -62,15 +66,15 @@ export function createClientVersionMonitor({ home = os.homedir(), env = process.
|
|
|
62
66
|
inspect = inspectInstalledClientVersions, persist = true, timeoutMs = 3000, now = Date.now, onChange = () => {}, ...options } = {}) {
|
|
63
67
|
const file = path.join(path.dirname(userSettingsPath({ home, env })), "client-versions.json");
|
|
64
68
|
let saved, writable = true, flight = null, closed = false;
|
|
65
|
-
let state = { checked_at: null, codex: [], claude: [], claude_unrecognized: false, persistence: "unknown" };
|
|
69
|
+
let state = { checked_at: null, codex: [], claude: [], antigravity: [], claude_unrecognized: false, persistence: "unknown" };
|
|
66
70
|
const snapshot = () => structuredClone(state);
|
|
67
71
|
async function load() {
|
|
68
72
|
if (saved) return saved;
|
|
69
73
|
try {
|
|
70
74
|
const value = JSON.parse(await readBoundedFile(file, { maxBytes: MAX_METADATA_BYTES, encoding: "utf8" }));
|
|
71
75
|
if (!fields(value, ["version", "apps"]) || value.version !== 1 || !value.apps || typeof value.apps !== "object" || Array.isArray(value.apps)
|
|
72
|
-
|| Object.entries(value.apps).length >
|
|
73
|
-
|
|
76
|
+
|| Object.entries(value.apps).length > MAX_APPS || Object.entries(value.apps).some(([id, entry]) =>
|
|
77
|
+
!validId(id) || !validEntry(entry))) throw new Error("Invalid saved App versions");
|
|
74
78
|
saved = value.apps;
|
|
75
79
|
} catch (error) {
|
|
76
80
|
if (error.code !== "ENOENT") writable = false;
|
|
@@ -80,12 +84,12 @@ export function createClientVersionMonitor({ home = os.homedir(), env = process.
|
|
|
80
84
|
}
|
|
81
85
|
async function run() {
|
|
82
86
|
const baseline = await load(), rows = await inspect({ home, env, platform, ...options });
|
|
83
|
-
if (!Array.isArray(rows) || rows.length >
|
|
87
|
+
if (!Array.isArray(rows) || rows.length > MAX_APPS) throw new Error("Invalid App version results");
|
|
84
88
|
const at = new Date(now()).toISOString(), next = { ...baseline }, updates = [];
|
|
85
|
-
const groups = { codex: [], claude: [] };
|
|
89
|
+
const groups = { codex: [], claude: [], antigravity: [] };
|
|
86
90
|
for (const row of rows) {
|
|
87
|
-
if (
|
|
88
|
-
|| !["codex", "claude"].includes(row.client) || !validVersion(row.version) || !optionalVersion(row.build) || !optionalVersion(row.cli_version)) continue;
|
|
91
|
+
if (!validId(row.id || "")
|
|
92
|
+
|| !["codex", "claude", "antigravity"].includes(row.client) || !validVersion(row.version) || !optionalVersion(row.build) || !optionalVersion(row.cli_version)) continue;
|
|
89
93
|
const current = installed(row), previous = baseline[row.id];let entry;
|
|
90
94
|
if (!previous) entry = { ...current, previous: null, changed_at: null };
|
|
91
95
|
else if (changed(previous, current)) {
|
|
@@ -116,10 +120,10 @@ export function createClientVersionMonitor({ home = os.homedir(), env = process.
|
|
|
116
120
|
const timeout = new Promise(resolve => { timer = setTimeout(() => resolve(null), timeoutMs); });
|
|
117
121
|
const result = Promise.race([work, timeout]).then(value => {
|
|
118
122
|
if (value) return value;
|
|
119
|
-
state = { ...state, checked_at: new Date(now()).toISOString(), codex: [], claude: [], persistence: "unavailable" };
|
|
123
|
+
state = { ...state, checked_at: new Date(now()).toISOString(), codex: [], claude: [], antigravity: [], persistence: "unavailable" };
|
|
120
124
|
return snapshot();
|
|
121
125
|
}).catch(() => {
|
|
122
|
-
state = { ...state, checked_at: new Date(now()).toISOString(), codex: [], claude: [], persistence: "unavailable" };
|
|
126
|
+
state = { ...state, checked_at: new Date(now()).toISOString(), codex: [], claude: [], antigravity: [], persistence: "unavailable" };
|
|
123
127
|
return snapshot();
|
|
124
128
|
}).finally(() => clearTimeout(timer));
|
|
125
129
|
task = { result };flight = task;
|
|
@@ -130,8 +134,8 @@ export function createClientVersionMonitor({ home = os.homedir(), env = process.
|
|
|
130
134
|
}
|
|
131
135
|
|
|
132
136
|
export function clientVersionChecks(snapshot) {
|
|
133
|
-
return ["codex", "claude"].map(client => {
|
|
134
|
-
const rows = snapshot?.[client] || [], name = client
|
|
137
|
+
return ["codex", "claude", "antigravity"].map(client => {
|
|
138
|
+
const rows = snapshot?.[client] || [], name = clientVersionName(client);
|
|
135
139
|
if (!rows.length) return { id: "client-versions", kind: "info", message: `${name}: installed version not observed` };
|
|
136
140
|
const versions = rows.map(row => `${row.name} ${row.version}${row.build ? ` (build ${row.build})` : ""}${row.cli_version ? `, CLI ${row.cli_version}` : ""}${row.changed_at ? `, changed ${row.changed_at}` : ""}`).join("; ");
|
|
137
141
|
return { id: "client-versions", kind: "info", message: `${name}: ${versions}. Running version and feature compatibility are not confirmed` };
|