codex-copilot-dx 1.4.22 → 1.4.24

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 CHANGED
@@ -1,8 +1,14 @@
1
1
  # CCDX
2
2
 
3
- Use your model services in **Codex App, Claude App and Claude Code** through one local gateway.
3
+ Use your model services in **Codex App, Claude App, Claude Code and Antigravity App** through one local gateway.
4
4
 
5
- On macOS, the optional Gemini integration adds compatible Copilot Gemini models to the original App's Antigravity. Ordinary Gemini chat keeps Google. The Antigravity page lists each model once, with its advertised reasoning levels shown in the same format as Codex and Claude. Refresh the catalog there or with `ccdx app antigravity models --refresh`. Existing clients keep their setup.
5
+ Antigravity can use compatible Copilot Gemini models with their advertised reasoning levels. Ordinary Gemini chat keeps Google. See [setup and connection checks](docs/REFERENCE.md#antigravity-in-gemini-app).
6
+
7
+ | Antigravity client | Integration |
8
+ | --- | --- |
9
+ | macOS Antigravity App or Gemini App | Integrated App detection, model routing and launch |
10
+ | Windows x64/ARM64 Antigravity App | Native launch path for the official 2.35.1 payloads. Signed-in App routing is pending live verification. |
11
+ | Antigravity standalone IDE or CLI | Separate clients outside this integration |
6
12
 
7
13
  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
14
 
@@ -33,7 +39,7 @@ On Windows, use `npm.cmd` or `ccdx.cmd` if PowerShell blocks npm-generated scrip
33
39
  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.
34
40
 
35
41
  1. **Model sources:** connect an account or API, read its models, choose allowed apps and save. Source tabs only change the view.
36
- 2. **Codex / Claude:** choose visible models, set a default and save. Preview and synchronize client settings when needed.
42
+ 2. **Codex / Claude / Antigravity:** choose visible models, set a default and save. For Antigravity, enable the integration and open the verified App from its page.
37
43
  3. **Overview / Requests:** check configuration, activity and errors.
38
44
  4. **Usage → Context:** inspect reported input, model windows and observed compactions from this run.
39
45
 
@@ -82,8 +88,6 @@ Use the Web UI for accounts, APIs, models, client access, input suggestions, nat
82
88
  - **Updates:** Settings → Install update downloads and verifies a stable release, then switches the installed service when idle. Busy work postpones the switch. Unmanaged launches require the installer or an installed command. [Details](docs/REFERENCE.md#installation-and-updates).
83
89
  - **App updates:** Checks & repairs and `ccdx doctor` show observed installed Codex, Claude and Antigravity versions. A version change does not by itself verify the running App or its integrations. [Details](docs/REFERENCE.md#checks-and-troubleshooting).
84
90
 
85
- Web UI activity updates through server push; the terminal uses the same in-process activity feed. Reconnecting restores current state and bounded recent records.
86
-
87
91
  The foreground terminal stops with **Ctrl+C**. Client configuration marked **Unchanged** means CCDX kept the existing settings. Configuration and successful model access are separate checks.
88
92
 
89
93
  If models are missing, check the selected source and app models first. After a client update or configuration change, fully quit and reopen that app. Use **Checks & repairs** or `ccdx doctor` for local diagnostics.
@@ -26,7 +26,9 @@ Antigravity tool schemas are converted to Chat Completions schemas. Object schem
26
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
27
 
28
28
 
29
- `gemini-app.mjs` verifies the installed App and prepares a process-local
29
+ `gemini-app.mjs` shares desktop launch planning with `application-control.mjs`.
30
+ `windows-antigravity-app.mjs` discovers native Windows installations and verifies the executable, application archive and language server before a launch.
31
+ The resulting plan prepares a process-local
30
32
  `CLOUD_CODE_URL` launch without editing its bundle or closing a running App.
31
33
  `antigravity-runtime.mjs` owns explicit enablement, source-history protection and
32
34
  the native management snapshot. The adapter loads it only for its management
@@ -1277,3 +1279,7 @@ The implementation takes the native/gateway-state ownership separation from [Mag
1277
1279
  `tool-activity.mjs` stores bounded, memory-only metadata behind each stream-performance observer. Existing parsed Responses items, Messages blocks and Gemini function calls supply tool names and scoped identifiers; no argument or output body is copied. The existing session/profile HMAC and application label isolate result matching. Results match call IDs, with a unique-name-only fallback for Gemini. Request completion changes generated calls to waiting, never to successful execution. Observable returned results, source failures and cancellation terminate the corresponding observations. Live response activity renews preparing observations with at most one notification per second per request. Missing evidence becomes unknown after 90 seconds, with a bounded late-result window. Snapshot reads perform lazy retention cleanup; there is no server polling loop.
1278
1280
 
1279
1281
  The WebUI consumes this metadata through the existing activity subscription. `dashboard/tool-activity.js` draws only the selected style, caches layout/theme measurements, caps drawing at 30 fps and DPR 1.5, pauses hidden/off-screen/reduced-motion views, and stops terminal cues within 0.9 seconds. Assembly line is the default; Beam ring and Grid are alternatives. Removed styles fall back to the default and Off retains state text. With no pending calls, conversation-purpose active requests supply processing/reply cues; internal diagnostics and terminal requests are excluded. Non-live request snapshots expire after six seconds. Local deadline timers stop stale activity even when the stream has no new events. Native controls, theme variables and the language dictionary preserve the existing UI contract. Existing `requests --active` and `requests tools` grammar also drive TUI discovery.
1282
+
1283
+ ## Dashboard assets
1284
+
1285
+ `dashboard-assets.mjs` owns the loopback asset allowlist and the ordered bootstrap bundle. The theme runs before paint; language and the bootstrap run in deferred order. Connection editors mount on their own views. Requests load only the selected drawing asset. Cold reads verify the installed package version around each file load.
package/docs/REFERENCE.md CHANGED
@@ -54,7 +54,7 @@ For installation and first use, start with the [README](../README.md). This refe
54
54
 
55
55
  Client IDs are `codex`, `claude-app` and `claude-code`. Source IDs are listed by `source list`. Read-only management commands support `--format table|plain|json`. They do not start an app or a gateway. Native image/suggestion status also reads local setup when the gateway is stopped; JSON includes the saved configuration flag and the same public details. Management operations need the running service; use `ccdx web` to start it without launching a client.
56
56
 
57
- The Codex, Claude App and Antigravity pages have a primary **Open app** action. A running App is focused, not launched again. **Reopen** requires confirmation and requests a normal exit; refusal, a changed process or multiple matching Apps stops the operation. Current desktop control covers macOS Codex, Claude App and Gemini/Antigravity, plus registered Codex and Claude installations on Windows. Claude Code remains a terminal client.
57
+ The Codex, Claude App and Antigravity pages have a primary **Open app** action. A running App is focused, not launched again. **Reopen** requires confirmation and requests a normal exit; refusal, a changed process or multiple matching Apps stops the operation. Current desktop control covers macOS Codex, Claude App and Gemini/Antigravity, plus registered Codex and Claude installations and known Antigravity App payloads on Windows. Claude Code remains a terminal client.
58
58
 
59
59
  **Open Codex when CCDX starts** is off by default. It takes effect on the next service start. `CCDX_AUTO_LAUNCH` explicitly overrides the saved preference; `0` disables and `1` enables it. `ccdx config set codex_auto_launch true --yes` also enables it. Explicit image preparation and opening remain available with automatic opening disabled.
60
60
 
@@ -74,7 +74,7 @@ Choose **Follow conversation model** to use an observed model from the same Code
74
74
  ## Antigravity in Gemini App
75
75
 
76
76
  The **Antigravity** page and `ccdx app antigravity status|models|enable|disable|open`
77
- manage the original macOS Gemini App. Enable requires acceptance of this data
77
+ manage the macOS Antigravity App or Gemini App and the native Windows App launch path described below. Enable requires acceptance of this data
78
78
  scope: Antigravity main answers follow the selected Google or Copilot model;
79
79
  unbound summaries, searches and image generation use GitHub Copilot. A known conversation retains its confirmed source, model and reasoning level for compression. Ordinary Gemini chat
80
80
  keeps its Google route. No OpenAI account or search fallback is used.
@@ -86,7 +86,7 @@ Copilot source page, or with `source github access --edit --apps codex,antigravi
86
86
  Choose its exposed models on the Antigravity page or with
87
87
  `app antigravity models --edit`. Each WebUI row represents one model. Compatible Gemini chat models come from the current GitHub catalog, rather than a fixed Carbon/Argon list. The Reasoning column lists advertised levels, including Hydrogen's `xhigh` when available. 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. Refresh on this page or run `app antigravity models --refresh` to read the upstream catalog through the existing GitHub refresh runtime. Refresh does not change saved choices, save drafts, restart clients or invoke inference; failed reads retain the last usable list.
88
88
 
89
- 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-hydrogen"]}` to expose all of its advertised levels, or individual `ccdx-copilot-...-<effort>` aliases to choose a subset. Existing Carbon/Argon aliases remain valid. Models without declared reasoning levels use one plain alias.
89
+ The native catalog keeps a distinct routing alias for each level. Catalogs with a recognized native grouping contract display one Copilot model with its advertised levels in the App picker. Other catalogs keep the separate aliases visible. JSON model output retains the 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-hydrogen"]}` to expose all of its advertised levels, or individual `ccdx-copilot-...-<effort>` aliases to choose a subset. Existing Carbon/Argon aliases remain valid. Models without declared reasoning levels use one plain alias.
90
90
  In the **New chat default** column, choose **Set default** on a Copilot model row, or choose **Use app default** to clear the preference on save. The row action uses `medium` if selected, otherwise the first selected level. `app antigravity models --edit` can choose an exact level; a model file can add `"default_model"` with a selected base ID or route alias, or `null` to clear. The gateway changes only the agent-default field in a compatible catalog; it leaves requests, existing conversation bindings, ordinary Gemini chat and background tasks unchanged. An unavailable saved default does not silently pick another Copilot model. The page reports when the catalog still needs to be loaded. Use **Reopen** in the Antigravity page when it indicates settings need loading. CCDX never reopens the app automatically. An observed connection or fetched catalog does not prove the app adopted the new default.
91
91
 
92
92
  On the **Antigravity** page, set **Copilot response-header timeout (s)** to 1–600 seconds and save, or leave it blank to use 180 seconds. An explicitly configured `CCDX_UPSTREAM_TIMEOUT_MS` supplies the default when the field is blank. The setting persists across restarts and applies when new Copilot generation requests send and wait for response headers. A wait already underway keeps its original deadline. When response headers arrive, the stream idle timer takes over. The same transition applies when the timeout uses its default. Queue, request-body, native Google, Codex and Claude retain their own limits. If `CCDX_ANTIGRAVITY_COPILOT_TIMEOUT_MS` is set at startup, the page shows that value and disables editing.
@@ -108,13 +108,15 @@ error rather than successful completion.
108
108
  This Copilot selection does not restrict Antigravity's original Google model directory. Google wire IDs such as `gemini-3.8-flash-tiered` can therefore appear in usage without being CCDX-added model choices. The recorded provider distinguishes Google and GitHub Copilot; the ID alone does not establish a background task or a fallback. Known conversation compaction retains its recorded source and model, including after a gateway restart. CCDX retains bounded per-session routing metadata with hashed session and source identifiers. Unbound title and summary jobs prefer Carbon Low when available, then a compatible model on the authorized Copilot source. Existing owner records without model metadata retain the previous background fallback when the App supplies no usable alias.
109
109
 
110
110
  `enable` saves CCDX settings and prepares its local source guard. `open --preview` shows the inspected application state without launching it.
111
- `open` starts a closed, verified Gemini App in `/Applications` or `~/Applications` with a process-local
111
+ `open` starts a closed, verified Antigravity App or Gemini App in `/Applications` or `~/Applications` on macOS with a process-local
112
112
  Antigravity endpoint. An already running App is focused. Reopen requests a normal
113
113
  exit after confirmation, through the same controller used by the page header. Existing gateway environment settings cause a
114
114
  conflict instead of being overwritten. The Gemini bundle, Google credentials,
115
115
  global proxy and certificates are untouched. Endpoint adoption remains
116
116
  unconfirmed until an Antigravity request is observed.
117
117
 
118
+ On Windows, install the official **Antigravity App** for x64 or ARM64 from [Google](https://antigravity.google/download), then run Windows-native CCDX. The native launcher verifies the executable, Electron application archive and language server against the corresponding official 2.35.1 installer payload. Unknown or modified builds remain unverified. Local launch preserves Windows and proxy settings and supplies the route only to the launched process. Existing gateway overrides and selected WSL backends cause a route conflict. Standalone Antigravity IDE and CLI remain separate. Windows launcher and bridge contracts have isolated coverage; signed-in model discovery, inference and native Google chat isolation still require live App acceptance.
119
+
118
120
  `disable` removes Copilot model access and refuses later Copilot/background
119
121
  requests without sending them to Google. Quit and reopen Gemini through CCDX
120
122
  after disabling to restore its native endpoint. This integration is separate
@@ -134,7 +136,7 @@ Each protocol observer retains at most 64 series of 64 request points and 16 com
134
136
 
135
137
  ## Observed tool calls
136
138
 
137
- **Requests → Tool and agent activity** offers Production line, Gear clock, Assembly line, Dual-lane sorter, Gantry transfer, Indexing table and Articulated robot arm. Production line is the default for new browsers and replaces unsupported preferences. Saved styles with the same name use the new drawings. Choose Off to keep status text without drawing. The setting is per browser. The display follows observed request and tool activity. Motion stops on completion, failure, cancellation, stale evidence, hidden views or reduced-motion settings. The pictures show activity and do not measure progress. Expand Call details for the full list. Recent requests show total time next to the timestamp, with details below each request.
139
+ **Requests → Tool and agent activity** offers Production line, Gear clock, Assembly line, Dual-lane sorter, Gantry transfer, Indexing table, Articulated robot arm and Warehouse pallet robots. Warehouse robots follow right-angle aisles and reserved intersection slots. Production line is the default for new browsers and replaces unsupported preferences. Saved styles with the same name use the new drawings. Choose Off to keep status text without drawing. The setting is per browser. The display follows observed request and tool activity. Motion stops on completion, failure, cancellation, stale evidence, hidden views or reduced-motion settings. The pictures show activity and do not measure progress. Expand Call details for the full list. Recent requests show total time next to the timestamp, with details below each request.
138
140
 
139
141
  On the Antigravity page, the top **Refresh** reads local setup and activity. **Refresh models** fetches the upstream catalog. Returning to the page retains unsaved selections and the last focused model control while status refreshes.
140
142
 
@@ -243,7 +245,7 @@ Catalog diagnostics distinguish local cached data from an online response and ex
243
245
  - **Request evidence:** use `ccdx requests show ID --format json` while the request is retained. The local request ID, outbound client ID and upstream request ID identify different stages. **Recent request issues → Failures over 24 hours** groups available failure metadata by hour, app, model and phase. `ccdx status --details --format json` includes the same bounded summary under `http_errors.history`.
244
246
  - **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.
245
247
  - **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.
246
- - **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. Claude capability synchronization uses the installed macOS App contract described below. An installed version alone does not establish native adoption. 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.
248
+ - **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 and detected Antigravity App version are 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. Claude capability synchronization uses the installed macOS App contract described below. An installed version alone does not establish native adoption. 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.
247
249
  - **Cache cleanup:** adding `--history` can break the next continuation. It does not delete client transcripts or generated images.
248
250
 
249
251
  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.
@@ -288,7 +290,7 @@ The initial internal ceiling is 128 concurrent requests per source/account. This
288
290
 
289
291
  Settings separates saved preferences from effective state. Auto-save applies changes by default; required restarts remain explicit. Restore-defaults creates a backup first and keeps accounts, keys, model plans and chats. CLI preference reset/restore uses its own service-only backup; it does not change browser appearance or replace the Web UI's backup.
290
292
 
291
- Use the button beside the CCDX wordmark to collapse the sidebar to icons. The browser remembers the layout for this dashboard address. The current page stays selected when the sidebar changes width.
293
+ Use the button beside the CCDX wordmark to collapse the sidebar to icons. Hover over or focus an icon to see its page name. Escape dismisses the tooltip. The browser remembers the layout for this dashboard address. The current page stays selected when the sidebar changes width.
292
294
 
293
295
  **Settings → Bark notifications** is collapsed by default. Enable it and paste the URL containing the device key from Bark. The minimum duration defaults to 30 minutes. Zero includes every eligible completed turn. Leave the title and description blank to use the name of the app that finished. The phone retrieves the matching public PNG from [Lobe Icons](https://github.com/lobehub/lobe-icons).
294
296
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.4.22",
3
+ "version": "1.4.24",
4
4
  "description": "Local gateway for Codex, Claude and Gemini Antigravity with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/adapter.mjs CHANGED
@@ -635,6 +635,7 @@ export async function startAdapter(port = 2026, host = "127.0.0.1", options = {}
635
635
  server.ccdxSnapshot = handler.snapshot;
636
636
  server.ccdxSubscribeActivity = handler.subscribeActivity;
637
637
  server.ccdxCloseActivity = handler.closeActivity;
638
+ server.ccdxDrainBackground = () => options.dashboardOptions?.serviceControl?.closeNotifications?.();
638
639
  server.ccdxBusy = handler.busy;
639
640
  server.ccdxExportState = handler.exportState;
640
641
  server.ccdxImportState = handler.importState;
@@ -4,6 +4,7 @@ import { MAX_UPSTREAM_CHAT_SUCCESS_BODY_BYTES } from "./http-transport.mjs";
4
4
  import { ToolArgumentDeltaGuard, upstreamChatStreamError } from "./stream-contract.mjs";
5
5
  import { observeSourceStreamFailure } from "./source-admission.mjs";
6
6
  import { sourceResponseAccepted } from "./source-response.mjs";
7
+ import { chatOutputParts } from "./chat-output-parts.mjs";
7
8
  import { MAX_OPAQUE_LENGTH } from "./antigravity-opaque-reasoning.mjs";
8
9
 
9
10
  const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -212,7 +213,7 @@ export function chatToAntigravity(response, originalNames, usage = mergeChatUsag
212
213
  if (!object(message)) throw invalid("Invalid upstream Chat response", 502);
213
214
  const parts = [];
214
215
  if (typeof message.reasoning_content === "string" && message.reasoning_content) parts.push({ text: message.reasoning_content, thought: true });
215
- if (typeof message.content === "string" && message.content) parts.push({ text: message.content });
216
+ for (const { text, thought } of chatOutputParts(message.content)) parts.push({ text, ...(thought ? { thought: true } : {}) });
216
217
  if (Array.isArray(message.tool_calls)) for (const call of message.tool_calls) parts.push(chatFunctionPart(call, originalNames));
217
218
  const finish = { stop: "STOP", tool_calls: "STOP", length: "MAX_TOKENS", content_filter: "SAFETY" }[choice.finish_reason];
218
219
  if (!finish) throw invalid("Upstream Chat response did not complete", 502);
@@ -245,11 +246,17 @@ export async function* chatStreamToAntigravity(response, originalNames, { onChun
245
246
  // Copilot sends a full replacement value in each such delta.
246
247
  opaque = delta.reasoning_opaque.length <= MAX_OPAQUE_LENGTH ? delta.reasoning_opaque : undefined;
247
248
  }
248
- for (const [key, thought] of [["reasoning_content", true], ["content", false], ["refusal", false]]) {
249
+ const parts = [];
250
+ for (const [key, thought] of [["reasoning_content", true], ["refusal", false]]) {
249
251
  if (delta[key] === undefined || delta[key] === null || delta[key] === "") continue;
250
252
  if (typeof delta[key] !== "string") throw invalid("Unsupported upstream Chat stream content", 502);
253
+ parts.push({ text: delta[key], thought });
254
+ }
255
+ const reasoning = parts.filter(part => part.thought);
256
+ const refusal = parts.filter(part => !part.thought);
257
+ for (const { text, thought } of [...reasoning, ...chatOutputParts(delta.content), ...refusal]) {
251
258
  if (!thought) visible = true;
252
- yield { response: { candidates: [{ index: 0, content: { role: "model", parts: [{ text: delta[key], ...(thought ? { thought: true } : {}) }] } }] } };
259
+ yield { response: { candidates: [{ index: 0, content: { role: "model", parts: [{ text, ...(thought ? { thought: true } : {}) }] } }] } };
253
260
  }
254
261
  if (delta.function_call) throw invalid("Unsupported upstream Chat function call", 502);
255
262
  if (delta.tool_calls !== undefined && !Array.isArray(delta.tool_calls)) throw invalid("Invalid upstream Chat tool calls", 502);
@@ -6,7 +6,7 @@ import {safeUpstreamResponseHeaders,upstreamRejectionHeaders} from "./upstream-h
6
6
  import {isLoopbackAddress,isLoopbackHostHeader} from "./security.mjs";
7
7
  import {antigravityToChat,chatToAntigravity,chatStreamToAntigravity,mergeChatUsage,chatReasoningTokens,parseAntigravityJSON} from "./antigravity-chat-bridge.mjs";
8
8
  import {createAntigravityOpaqueReasoning} from "./antigravity-opaque-reasoning.mjs";
9
- import {ANTIGRAVITY_MODEL_PREFIX,ANTIGRAVITY_NATIVE_PREFIX,antigravityCopilotModels,hasAntigravityAgentDefault,mergeAntigravityModels} from "./antigravity-models.mjs";
9
+ import {ANTIGRAVITY_MODEL_PREFIX,ANTIGRAVITY_NATIVE_PREFIX,antigravityCopilotModels,groupedAntigravityRoutes,hasAntigravityAgentDefault,mergeAntigravityModels} from "./antigravity-models.mjs";
10
10
  import {createPrivacyTextFragments} from "./privacy-stream.mjs";
11
11
  import {createGoogleResponseObserver,googleUsageEvent} from "./antigravity-usage.mjs";
12
12
  import {currentRequestContext,observeRequestedModel} from "./request-context.mjs";
@@ -61,7 +61,8 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
61
61
  if(![GOOGLE_ORIGIN,"https://cloudcode-pa.googleapis.com"].includes(googleOrigin))throw new Error("Unrecognized Google control origin");
62
62
  const acquireControl=createRequestAdmission({maxBytes:4*CONTROL_BODY_BYTES,maxQueued:8});
63
63
  const opaqueReasoning=createAntigravityOpaqueReasoning();
64
- let active=0,observed=false,catalogModels=null,catalogDefaultSupported=null,catalogDefaultModel=null;const nativeWindows=new Map();
64
+ let active=0,observed=false,catalogModels=null,catalogDefaultSupported=null,catalogDefaultModel=null;
65
+ const nativeWindows=new Map(),catalogGroups=new Map();
65
66
  const counts={total:0,google:0,copilot:0,search:0,images:0,failed:0};
66
67
  const handler=async(req,res)=>{
67
68
  const startedAt=performance.timeOrigin+performance.now(),abort=createRequestAbort(req,res);let commitBinding,release=()=>{},releaseControl,session,body,request,converted,finish,phase="validation",usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
@@ -153,9 +154,16 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
153
154
  const value=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:8*1024*1024,signal:abort.signal,label:"Google model catalog"}));
154
155
  nativeWindows.clear();for(const[id,entry]of Object.entries(value.models||{}).slice(0,256))if(Number.isSafeInteger(entry?.maxTokens)&&entry.maxTokens>0){nativeWindows.set(id,entry.maxTokens);if(typeof entry.model==="string")nativeWindows.set(entry.model,entry.maxTokens)}
155
156
  const merged=mergeAntigravityModels(value,models(config),selectedModels(config),defaultModel(config),nativeModels(config));
157
+ catalogGroups.clear();
158
+ for(const [id,group] of Object.entries(merged.groupedModels||{})){
159
+ if(!id.startsWith(ANTIGRAVITY_MODEL_PREFIX)||Object.hasOwn(value.groupedModels??{},id))continue;
160
+ const routes=groupedAntigravityRoutes(id,group,merged.models);
161
+ if(routes.defaultAlias)catalogGroups.set(id,routes);
162
+ }
156
163
  catalogDefaultSupported=hasAntigravityAgentDefault(value);
157
164
  catalogDefaultModel=catalogDefaultSupported&&merged.defaultAgentModelId.startsWith(ANTIGRAVITY_MODEL_PREFIX)?merged.defaultAgentModelId:null;
158
- catalogModels=Object.keys(merged.models).filter(id=>id.startsWith(ANTIGRAVITY_MODEL_PREFIX)||id.startsWith(ANTIGRAVITY_NATIVE_PREFIX));
165
+ catalogModels=Object.keys(merged.models).filter(id=>!catalogGroups.has(id)&&
166
+ (id.startsWith(ANTIGRAVITY_MODEL_PREFIX)||id.startsWith(ANTIGRAVITY_NATIVE_PREFIX)));
159
167
  res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"});res.end(JSON.stringify(merged));return;
160
168
  }
161
169
  const nativeStreaming=/text\/event-stream/i.test(upstream.headers.get("content-type")||"");
@@ -289,7 +297,14 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
289
297
  }catch(error){sourceResponseFailed(upstream);await cancelSourceResponse(upstream).catch(()=>{});markResponseErrorOrigin("upstream_event");throw error;}
290
298
  return;
291
299
  }
292
- const copilotModels=antigravityCopilotModels(models(config)),selected=copilotModels.find(model=>model.id===body.model&&(selection===null||selection.includes(model.id)));
300
+ const copilotModels=antigravityCopilotModels(models(config)),group=catalogGroups.get(body.model);
301
+ let selectedId=body.model;
302
+ if(group){
303
+ const effort=body.request?.generationConfig?.thinkingConfig?.thinkingLevel;
304
+ selectedId=effort===undefined?group.defaultAlias:typeof effort==="string"?group.aliases.get(effort.toLowerCase()):null;
305
+ if(!selectedId)throw httpError("Unsupported Antigravity reasoning level",400);
306
+ }
307
+ const selected=copilotModels.find(model=>model.id===selectedId&&(selection===null||selection.includes(model.id)));
293
308
  if((body.requestType==="agent"||compactBinding?.source==="google")&&!selected){
294
309
  if(body.model.startsWith(ANTIGRAVITY_MODEL_PREFIX))throw httpError("The selected Copilot model is unavailable",503);
295
310
  const hasSession=body.requestType==="agent"||body.request?.labels?.root_cascade_id||body.request?.labels?.cascade_id;
@@ -332,7 +347,8 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
332
347
  }
333
348
  }
334
349
  if(!target)throw httpError(bound?"The conversation model is unavailable for Antigravity":"No eligible Copilot model is available for Antigravity background tasks",503);
335
- if(body.requestType==="agent")commitBinding=prepareConversationBinding(body,"github",profile,startedAt);
350
+ if(body.requestType==="agent")commitBinding=prepareConversationBinding(
351
+ body.model===target.id?body:{...body,model:target.id},"github",profile,startedAt);
336
352
  const stream=method==="streamGenerateContent";usageModel=target.model;usageMode=stream?"sse":"json";usageProvider="github";
337
353
  const conversation=request.labels?.root_cascade_id||request.labels?.cascade_id;
338
354
  const scope=body.requestType==="agent"&&typeof profile==="string"&&profile&&typeof conversation==="string"&&conversation.length<=160
@@ -61,15 +61,42 @@ export function hasAntigravityAgentDefault(catalog) {
61
61
  return typeof id==="string"&&!!catalog.models&&Object.hasOwn(catalog.models,id);
62
62
  }
63
63
 
64
+ function nativeGrouping(catalog) {
65
+ const groups = catalog.groupedModels;
66
+ if (!groups || typeof groups !== "object" || Array.isArray(groups) || !Array.isArray(catalog.agentModelSorts)) return null;
67
+ const listed = new Set(catalog.agentModelSorts.flatMap(sort =>
68
+ Array.isArray(sort?.groups) ? sort.groups.flatMap(group => Array.isArray(group?.modelIds) ? group.modelIds : []) : []));
69
+ for (const [id, group] of Object.entries(groups)) {
70
+ if (!listed.has(id) || !Array.isArray(group?.supportedThinkingLevels)) continue;
71
+ const proved = group.supportedThinkingLevels.find(level => typeof level?.thinkingSuffix === "string" &&
72
+ /^(?:-)?[a-z][a-z0-9-]{0,30}$/.test(level.thinkingSuffix) &&
73
+ (Object.hasOwn(catalog.models, id + level.thinkingSuffix) || Object.hasOwn(catalog.models, id + "-" + level.thinkingSuffix)));
74
+ if (proved) return { dashedSuffix: proved.thinkingSuffix.startsWith("-"), parentInModels: Object.hasOwn(catalog.models, id) };
75
+ }
76
+ return null;
77
+ }
78
+
79
+ export function groupedAntigravityRoutes(id, group, models) {
80
+ const aliases = new Map((group.supportedThinkingLevels || []).flatMap(({thinkingSuffix:suffix})=>{
81
+ const effort=suffix.replace(/^-/,""),alias=id+"-"+effort;
82
+ return Object.hasOwn(models,alias)?[[effort,alias]]:[];
83
+ }));
84
+ return {aliases,defaultAlias:aliases.get(group.defaultThinkingSuffix?.replace(/^-/,""))};
85
+ }
86
+
64
87
  export function mergeAntigravityModels(googleCatalog,copilotCatalog,selection=null,defaultModel=null,nativeModels=[]) {
65
88
  if(!googleCatalog?.models||typeof googleCatalog.models!=="object"||Array.isArray(googleCatalog.models))throw new Error("Unrecognized Google model catalog");
66
89
  const entries=[...antigravityCopilotModels(copilotCatalog).filter(model=>selection===null||selection.includes(model.id)),...nativeModels],models={...googleCatalog.models};
67
90
  if(!entries.length)return googleCatalog;
68
91
  const used=new Set(Object.values(models).map(model=>model?.model));let next=500;
69
- for(const entry of entries){
92
+ const modelId=()=>{
70
93
  while(next<600&&used.has("MODEL_PLACEHOLDER_M"+next))next++;
71
- if(next>=600||Object.hasOwn(models,entry.id))throw new Error("Antigravity model catalog has no free client identifiers");
72
- const model="MODEL_PLACEHOLDER_M"+next++;used.add(model);
94
+ if(next>=600)return null;
95
+ const model="MODEL_PLACEHOLDER_M"+next++;used.add(model);return model;
96
+ };
97
+ for(const entry of entries){
98
+ const model=modelId();
99
+ if(!model||Object.hasOwn(models,entry.id))throw new Error("Antigravity model catalog has no free client identifiers");
73
100
  models[entry.id]={displayName:entry.displayName,model,maxTokens:entry.maxTokens,maxOutputTokens:entry.maxOutputTokens,
74
101
  supportsImages:entry.supportsImages,supportsThinking:Boolean(entry.effort),apiProvider:"API_PROVIDER_GOOGLE_GEMINI"};
75
102
  }
@@ -77,7 +104,32 @@ export function mergeAntigravityModels(googleCatalog,copilotCatalog,selection=nu
77
104
  // Gemini App reads only the first group in the Recommended sort.
78
105
  const sort=sorts.find(item=>item.displayName?.toLowerCase()==="recommended")||sorts[0];
79
106
  sort.groups??=[];sort.groups[0]??={modelIds:[]};
80
- sort.groups[0].modelIds=[...(sort.groups[0].modelIds||[]),...entries.map(entry=>entry.id)];
81
- return {...googleCatalog,models,agentModelSorts:sorts,
107
+ const contract=nativeGrouping(googleCatalog), parents=new Map();
108
+ let groupedModels;
109
+ if(contract){
110
+ const families=new Map();
111
+ for(const row of entries){
112
+ if(!row.effort||!row.id.startsWith(ANTIGRAVITY_MODEL_PREFIX))continue;
113
+ const rows=families.get(row.model)||[];rows.push(row);families.set(row.model,rows);
114
+ }
115
+ groupedModels={...googleCatalog.groupedModels};
116
+ for(const [family,rows] of families){
117
+ const parent=ANTIGRAVITY_MODEL_PREFIX+family;
118
+ if(rows.length<2||Object.hasOwn(models,parent)||Object.hasOwn(groupedModels,parent))continue;
119
+ const chosen=rows.find(row=>row.id===defaultModel)||rows.find(row=>row.effort==="medium")||rows[0];
120
+ const displayName=chosen.displayName.split(" · Copilot")[0]+" · Copilot";
121
+ if(contract.parentInModels){
122
+ const model=modelId();if(!model)continue;
123
+ models[parent]={...models[chosen.id],model,displayName};
124
+ }
125
+ const suffix=effort=>(contract.dashedSuffix?"-":"")+effort;
126
+ groupedModels[parent]={displayName,defaultThinkingSuffix:suffix(chosen.effort),supportedThinkingLevels:rows.map(row=>({
127
+ thinkingSuffix:suffix(row.effort),thinkingDisplayName:row.effort[0].toUpperCase()+row.effort.slice(1),
128
+ }))};
129
+ for(const row of rows)parents.set(row.id,parent);
130
+ }
131
+ }
132
+ sort.groups[0].modelIds=[...(sort.groups[0].modelIds||[]),...new Set(entries.map(entry=>parents.get(entry.id)||entry.id))];
133
+ return {...googleCatalog,models,agentModelSorts:sorts,...(groupedModels?{groupedModels}:{}),
82
134
  ...(hasAntigravityAgentDefault(googleCatalog)&&entries.some(entry=>entry.id===defaultModel)?{defaultAgentModelId:defaultModel}:{})};
83
135
  }
@@ -7,6 +7,7 @@ import {createAntigravityHandler} from "./antigravity-handler.mjs";
7
7
  import {createAntigravityImages} from "./antigravity-images.mjs";
8
8
  import {createCopilotWeb} from "./copilot-web.mjs";
9
9
  import {inspectGeminiApp,planGeminiAppLaunch} from "./gemini-app.mjs";
10
+ import {launchWindowsAntigravity} from "./windows-antigravity-app.mjs";
10
11
  import {readUserSettings,userSettingsPath} from "./user-settings.mjs";
11
12
  import {readAccessSettings} from "./access-settings.mjs";
12
13
  import {readClientGatewayKeys} from "./client-gateway-keys.mjs";
@@ -26,8 +27,8 @@ const nativeSourceKey="gemini_antigravity_native_source";
26
27
  const validTimeout=value=>Number.isSafeInteger(value)&&value>=1&&value<=600;
27
28
  const validAlias=id=>typeof id==="string"&&/^ccdx-copilot-[a-z0-9._-]{1,140}$/.test(id);
28
29
 
29
- export function createAntigravityRuntime({client,models=()=>[],refreshModels,privacy,home=os.homedir(),env=process.env,inspect=inspectGeminiApp,
30
- exec=execute,searchFn,imageFn,guardSource,googleFetch,acquireRequest,applicationControl,readToken=()=>readSavedGithubToken(home),
30
+ export function createAntigravityRuntime({client,models=()=>[],refreshModels,privacy,home=os.homedir(),env=process.env,platform=process.platform,inspect=inspectGeminiApp,
31
+ exec=execute,launchWindows=launchWindowsAntigravity,searchFn,imageFn,guardSource,googleFetch,acquireRequest,applicationControl,readToken=()=>readSavedGithubToken(home),
31
32
  upstreamTimeoutMs=180000,copilotTimeoutMs,nativeSources=()=>[],getSource=()=>null,...timeouts}={}) {
32
33
  const options={home,env},guard=createConversationSourceGuard(options);
33
34
  const web=searchFn?null:createCopilotWeb({client,readToken});
@@ -178,13 +179,15 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
178
179
  }else await applicationControl.check("antigravity",true);
179
180
  return snapshot();
180
181
  }
181
- app=await inspect();route=baseUrl+"/antigravity";
182
+ app=await inspect({home,env,platform,exec});route=baseUrl+"/antigravity";
182
183
  if(["open","preview"].includes(operation)){
183
184
  const config=settings();
184
- const plan=config.enabled||config.native_source?planGeminiAppLaunch(app,{cloudCodeUrl:route,env,home}):app.status==="stopped"?{status:"prepared",command:"/usr/bin/open",args:["-a",app.app]}:{status:app.status==="running"?"needs_app_relaunch":app.status};
185
+ const plan=planGeminiAppLaunch(app,{cloudCodeUrl:config.enabled||config.native_source?route:undefined,env,home,platform});
185
186
  lastOperation={action:operation,status:plan.status};
186
187
  if(operation==="open"&&plan.status==="prepared"){
187
- await exec(plan.command,plan.args,{encoding:"utf8",timeout:5000,maxBuffer:4096});lastOperation.status="opened";app={...app,status:"starting"};
188
+ if(platform==="win32")await launchWindows(plan);
189
+ else await exec(plan.command,plan.args,{encoding:"utf8",timeout:5000,maxBuffer:4096});
190
+ lastOperation.status="opened";app={...app,status:"starting"};
188
191
  }
189
192
  if(operation==="preview"&&plan.status==="prepared")lastOperation.plan={command:plan.command,args:plan.args};
190
193
  }
@@ -6,12 +6,13 @@ import { inspectApplicationConfiguration } from "./application-configuration.mjs
6
6
  import { createApplicationEvidence } from "./application-evidence.mjs";
7
7
  import { planGeminiAppLaunch, inspectGeminiApp } from "./gemini-app.mjs";
8
8
  import { readUserSettings } from "./user-settings.mjs";
9
+ import { launchWindowsAntigravity } from "./windows-antigravity-app.mjs";
9
10
 
10
11
  const execute = promisify(execFile), ids = ["codex", "claude_app", "antigravity"];
11
12
  export function createApplicationControl({ providerRuntime, clientIntegration, imageHostState, env = process.env, home,
12
13
  platform = process.platform, port = 2026, host = "127.0.0.1", now = Date.now, exec = execute, wait = sleep,
13
14
  inspect = inspectApplicationProcesses, connections = applicationConnections, control = controlApplicationProcess,
14
- inspectGemini = inspectGeminiApp,
15
+ inspectGemini = inspectGeminiApp, launchWindowsGemini = launchWindowsAntigravity,
15
16
  configuration = inspectApplicationConfiguration, openCodexApp, evidence = providerRuntime?.applicationEvidence || createApplicationEvidence({ now }) } = {}) {
16
17
  const options = { env, home, platform, exec };
17
18
  const states = Object.fromEntries(ids.map(id => [id, { status: "unknown", connection: "pending" }]));
@@ -56,6 +57,10 @@ export function createApplicationControl({ providerRuntime, clientIntegration, i
56
57
  if (operation === "restart" && expectedPid !== undefined && (expectedPid !== app?.pid || expectedStarted !== app?.started)) return { status: "app_changed", app: state };
57
58
  if (["unknown", "multiple", "unsupported", "not_installed"].includes(state.status)) return { status: state.status, app: state };
58
59
  if (state.status === "starting") return { status: "opening", app: state };
60
+ if (platform === "win32" && id === "antigravity" && state.status === "running") {
61
+ const verified = await inspectGemini({ ...options, app: app.app });
62
+ if (verified.status !== "running" || !verified.pids.includes(app.pid)) return { status: "app_changed", app: state };
63
+ }
59
64
  if (state.status === "running" && operation !== "restart") {
60
65
  if (state.needs_reload && operation !== "focus") return { status: "needs_app_relaunch", app: state };
61
66
  const result = await control(app, "focus", options);
@@ -84,10 +89,13 @@ export function createApplicationControl({ providerRuntime, clientIntegration, i
84
89
  handled = true;
85
90
  }
86
91
  }
87
- if (!handled && platform === "darwin") {
88
- const plan = id === "antigravity" ? await antigravityPlan(app) : { status: "prepared", command: "/usr/bin/open", args: ["-a", app.app] };
92
+ if (!handled && id === "antigravity") {
93
+ const plan = await antigravityPlan(app);
89
94
  if (plan.status !== "prepared") return { status: plan.status, app: states[id] };
90
- await exec(plan.command, plan.args, { encoding: "utf8", timeout: 5000, maxBuffer: 4096 });
95
+ if (platform === "win32") await launchWindowsGemini(plan);
96
+ else await exec(plan.command, plan.args, { encoding: "utf8", timeout: 5000, maxBuffer: 4096 });
97
+ } else if (!handled && platform === "darwin") {
98
+ await exec("/usr/bin/open", ["-a", app.app], { encoding: "utf8", timeout: 5000, maxBuffer: 4096 });
91
99
  } else if (!handled && platform === "win32") {
92
100
  if (app.target.startsWith("shell:AppsFolder\\")) await exec("explorer.exe", [app.target], { encoding: "utf8", timeout: 5000, maxBuffer: 4096, windowsHide: true });
93
101
  else await exec(app.target, [], { encoding: "utf8", timeout: 5000, maxBuffer: 4096, windowsHide: true });
@@ -101,11 +109,10 @@ export function createApplicationControl({ providerRuntime, clientIntegration, i
101
109
  const config = readUserSettings({ env, home, strict: true });
102
110
  return config.gemini_antigravity_enabled === true || typeof config.gemini_antigravity_native_source === "string";
103
111
  };
104
- if (!bridgeEnabled()) return { status: "prepared", command: "/usr/bin/open", args: ["-a", app.app] };
112
+ if (platform === "darwin" && !bridgeEnabled()) return { status: "prepared", command: "/usr/bin/open", args: ["-a", app.app] };
105
113
  const verified = await inspectGemini({ ...options, app: app.app });
106
114
  if (verified.status !== "stopped") return { status: verified.status === "running" ? "app_changed" : verified.status };
107
- if (!bridgeEnabled()) return { status: "prepared", command: "/usr/bin/open", args: ["-a", app.app] };
108
- return planGeminiAppLaunch(verified, { cloudCodeUrl: `http://${host}:${port}/antigravity`, env, home });
115
+ return planGeminiAppLaunch(verified, { cloudCodeUrl: bridgeEnabled() ? `http://${host}:${port}/antigravity` : undefined, env, home, platform });
109
116
  }
110
117
  return { snapshot, evidence, check, busy: () => operations > 0,
111
118
  async previewAntigravity() {
@@ -4,12 +4,14 @@ import path from "node:path";
4
4
  import { execFile } from "node:child_process";
5
5
  import { promisify } from "node:util";
6
6
  import { installedWindowsPredictionAppAsync } from "./native-prediction-windows.mjs";
7
+ import { inspectWindowsAntigravity } from "./windows-antigravity-app.mjs";
8
+ import { macAntigravityBundles } from "./macos-antigravity-app.mjs";
7
9
 
8
10
  const execute = promisify(execFile);
9
11
  const definitions = {
10
12
  codex: { bundles: ["Codex.app", "ChatGPT.app"], id: "com.openai.codex", executables: ["Codex", "ChatGPT"] },
11
13
  claude_app: { bundles: ["Claude.app"], id: "com.anthropic.claudefordesktop", executables: ["Claude"] },
12
- antigravity: { bundles: ["Gemini.app"], id: "com.google.GeminiMacOS", executables: ["Gemini"] },
14
+ antigravity: { bundles: Object.keys(macAntigravityBundles) },
13
15
  };
14
16
  const runOptions = { encoding: "utf8", timeout: 3000, maxBuffer: 4 * 1024 * 1024, windowsHide: true };
15
17
  const metadataEnvironment = env => ({ ...Object.fromEntries(["PATH", "SystemRoot", "WINDIR", "TEMP", "TMP", "LOCALAPPDATA", "APPDATA", "USERPROFILE", "HOME", "TZ"]
@@ -31,7 +33,8 @@ export function processFamily(processes, root) {
31
33
  }
32
34
 
33
35
  export async function inspectApplicationProcesses({ platform = process.platform, home = os.homedir(), env = process.env,
34
- exec = execute, discoverWindows = installedWindowsPredictionAppAsync, applicationsRoot = "/Applications" } = {}) {
36
+ exec = execute, discoverWindows = installedWindowsPredictionAppAsync, discoverWindowsAntigravity = inspectWindowsAntigravity,
37
+ applicationsRoot = "/Applications" } = {}) {
35
38
  if (!["darwin", "win32"].includes(platform)) return { apps: Object.fromEntries(Object.keys(definitions).map(id => [id, { status: "unsupported" }])), processes: [] };
36
39
  const apps = {}, processes = [];
37
40
  if (platform === "darwin") {
@@ -47,23 +50,30 @@ export async function inspectApplicationProcesses({ platform = process.platform,
47
50
  try { await fs.access(file); } catch { continue; }
48
51
  const result = await exec("/usr/bin/plutil", ["-convert", "json", "-o", "-", file], { ...runOptions, maxBuffer: 65536 });
49
52
  const info = JSON.parse(result.stdout);
50
- if (info.CFBundleIdentifier !== definition.id || !definition.executables.includes(info.CFBundleExecutable)) continue;
51
- installed.push({ app, target: app, identity: definition.id, executable: path.join(app, "Contents/MacOS", info.CFBundleExecutable), version: info.CFBundleShortVersionString });
53
+ const antigravity = id === "antigravity" ? macAntigravityBundles[bundle] : null;
54
+ const identity = antigravity?.identifier ?? definition.id;
55
+ if (info.CFBundleIdentifier !== identity ||
56
+ !(antigravity ? antigravity.executable === info.CFBundleExecutable : definition.executables.includes(info.CFBundleExecutable))) continue;
57
+ if (antigravity) try { await fs.access(path.join(app, antigravity.helper)); } catch { continue; }
58
+ installed.push({ app, target: app, identity, executable: path.join(app, "Contents/MacOS", info.CFBundleExecutable), version: info.CFBundleShortVersionString });
52
59
  }
53
60
  const running = installed.filter(info => processes.some(row => row.command === info.executable));
54
61
  apps[id] = running.length > 1 ? { status: "multiple" } : running[0] || installed[0] || { status: "not_installed" };
55
62
  }
56
63
  } else {
57
- const result = await exec("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", windowsInventory], { ...runOptions, env: metadataEnvironment(env) });
64
+ const [result, codex, antigravity] = await Promise.all([
65
+ exec("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", windowsInventory], { ...runOptions, env: metadataEnvironment(env) }),
66
+ Promise.resolve().then(() => discoverWindows({ env })).catch(() => null),
67
+ Promise.resolve().then(() => discoverWindowsAntigravity({ env, exec })).catch(() => ({ status: "unknown" })),
68
+ ]);
58
69
  const inventory = JSON.parse(result.stdout);
59
70
  for (const row of inventory.processes || []) if (Number.isSafeInteger(row.pid) && row.pid > 0 && Number.isFinite(Date.parse(row.started))) processes.push(row);
60
- let codex;try { codex = await discoverWindows({ env }); } catch {}
61
71
  apps.codex = codex ? { app: codex.app, target: codex.app, executable: codex.app } : { status: "not_installed" };
62
72
  const claude = inventory.claude;
63
73
  apps.claude_app = claude && path.win32.isAbsolute(claude.app) && path.win32.basename(claude.app).toLowerCase() === "claude.exe"
64
74
  && (claude.target === claude.app || /^shell:AppsFolder\\[A-Za-z0-9._-]+![A-Za-z0-9._-]+$/.test(claude.target))
65
75
  ? { app: claude.app, target: claude.target, executable: claude.app } : { status: "not_installed" };
66
- apps.antigravity = { status: "unsupported" };
76
+ apps.antigravity = antigravity;
67
77
  }
68
78
  for (const info of Object.values(apps)) if (info.executable) {
69
79
  const same = command => platform === "win32" ? command?.toLowerCase() === info.executable.toLowerCase() : command === info.executable;
@@ -165,7 +165,8 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
165
165
  const antigravity = path.join(home, ".gemini", "antigravity");
166
166
  let timer, lastResult = null, closed = false, running = false, watching = false, since = now();
167
167
  let settings = readSettings(), antigravityCatalog, insecureRef;
168
- let stopWatcher, antigravityScan;
168
+ let stopWatcher, antigravityScan, scanFlight, closeFlight;
169
+ const shutdown = new AbortController();
169
170
  const scanned = new Map();
170
171
 
171
172
  function readSettings() {
@@ -238,14 +239,15 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
238
239
  if (closed || snapshot !== settings) return;
239
240
  try { if (!claim(event)) return; }
240
241
  catch { lastResult = "ledger_failed";return; }
242
+ const signal = AbortSignal.any([shutdown.signal, AbortSignal.timeout(5000)]);
241
243
  const result = await fetchImpl(destination.endpoint, {
242
- method: "POST", headers: { "Content-Type": "application/json" }, redirect: "error", signal: AbortSignal.timeout(5000),
244
+ method: "POST", headers: { "Content-Type": "application/json" }, redirect: "error", signal,
243
245
  body: JSON.stringify({ device_key: destination.deviceKey, ...notificationMessage(snapshot, event) }),
244
246
  });
245
- const reply = await readBoundedResponseText(result, { maxBytes: 4096, label: "Bark response" });
246
- if (snapshot === settings) lastResult = result.ok && record(reply)?.code === 200 ? "sent" : "failed";
247
+ const reply = await readBoundedResponseText(result, { maxBytes: 4096, label: "Bark response", signal });
248
+ if (!closed && snapshot === settings) lastResult = result.ok && record(reply)?.code === 200 ? "sent" : "failed";
247
249
  } catch {
248
- if (snapshot === settings) lastResult = "failed";
250
+ if (!closed && snapshot === settings) lastResult = "failed";
249
251
  }
250
252
  }
251
253
 
@@ -332,7 +334,7 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
332
334
 
333
335
  function schedule(interval = scanIntervalMs) {
334
336
  clearTimeout(timer);
335
- if (!closed && settings.enabled) timer = setTimeout(() => { void scan(); }, interval).unref();
337
+ if (!closed && settings.enabled) timer = setTimeout(() => { scanFlight = scan(); }, interval).unref();
336
338
  }
337
339
 
338
340
  function watchAntigravityStop() {
@@ -385,6 +387,15 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
385
387
  schedule(0);
386
388
  return snapshot();
387
389
  },
388
- close() { closed = true;clearTimeout(timer);stopWatcher?.close();secretStore.close?.(); },
390
+ close() {
391
+ if (closeFlight) return closeFlight;
392
+ closed = true;clearTimeout(timer);stopWatcher?.close();shutdown.abort();
393
+ let deadline;
394
+ closeFlight = Promise.race([
395
+ Promise.allSettled([scanFlight, antigravityScan]),
396
+ new Promise(resolve => { deadline = setTimeout(resolve, 5000).unref(); }),
397
+ ]).finally(() => { clearTimeout(deadline);secretStore.close?.(); });
398
+ return closeFlight;
399
+ },
389
400
  };
390
401
  }
@@ -0,0 +1,20 @@
1
+ import { invalidUpstreamStream } from "./stream-contract.mjs";
2
+
3
+ function unsupported() {
4
+ throw invalidUpstreamStream("Unsupported upstream Chat stream content");
5
+ }
6
+
7
+ export function chatOutputParts(content) {
8
+ if (content == null || content === "") return [];
9
+ if (typeof content === "string") return [{ text: content, thought: false }];
10
+ if (!Array.isArray(content)) unsupported();
11
+ return content.flatMap(part => {
12
+ if (part?.type === "text" && typeof part.text === "string") return [{ text: part.text, thought: false }];
13
+ if (part?.type === "thinking") {
14
+ if (typeof part.thinking === "string") return [{ text: part.thinking, thought: true }];
15
+ if (Array.isArray(part.thinking) && part.thinking.every(chunk => chunk?.type === "text" && typeof chunk.text === "string"))
16
+ return part.thinking.map(chunk => ({ text: chunk.text, thought: true }));
17
+ }
18
+ return unsupported();
19
+ }).filter(part => part.text);
20
+ }