codex-copilot-dx 1.4.12 → 1.4.13

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
@@ -58,10 +58,10 @@ Model availability depends on your account and service. Microsoft 365 also requi
58
58
  | Preview client setup | `ccdx app claude-app sync --preview` |
59
59
  | Set up Antigravity | `ccdx app antigravity status` / `enable` / `open` |
60
60
  | Inspect compression | `ccdx compact status` / `ccdx compact enable` / `ccdx compact disable` |
61
- | Inspect failures | `ccdx requests --failed` |
61
+ | Inspect failures | `ccdx requests --failed` / `ccdx requests show ID --format json` |
62
62
  | Inspect observed tool calls | `ccdx requests tools` / `ccdx requests tools --active` |
63
63
  | Inspect active model requests | `ccdx requests --active` |
64
- | Capture one upstream error | `ccdx requests diagnose --source api_work --model model-id --yes` |
64
+ | Capture one upstream Messages 400/422 | `ccdx requests diagnose --source api_work --model model-id --yes` |
65
65
  | Read usage | `ccdx usage` / `ccdx usage --provider google --days 7` / `ccdx usage --purpose diagnostic` / `ccdx usage --scope run` |
66
66
  | Inspect preferences | `ccdx config show --effective` |
67
67
  | Inspect local masking | `ccdx config privacy status` |
@@ -80,7 +80,7 @@ Use the Web UI for accounts, APIs, models, client access, input suggestions, nat
80
80
  - **Input suggestions:** new integrations attempt setup by default when Codex is closed. Saved off choices are retained. The Web UI can enable, disable, finish setup, open Codex and repair the bridge. Setup synchronizes Show predictions, adds App-profile trust and locally decrypts the prediction hosts' HTTPS traffic. App/thread eligibility still applies. [Details](docs/REFERENCE.md#optional-native-predictions).
81
81
  - **Images:** Codex native host tools use the selected GitHub image model, with GPT Image 2.5 Flare as the default. Images start enabled; saved off choices are retained. On macOS with Codex 0.166+, fully quit a running App that lacks the host, start Codex through CCDX, and use a new chat. ChatGPT sign-in and Apps are retained. The Web UI provides model selection without an extra API key, MCP or CCDX image skill. [Details](docs/REFERENCE.md#native-image-generation).
82
82
  - **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
- - **App updates:** Checks & repairs and `ccdx doctor` show observed installed Codex and Claude versions. A version change does not by itself verify the running App or its integrations. [Details](docs/REFERENCE.md#checks-and-troubleshooting).
83
+ - **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
84
 
85
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
86
 
@@ -49,6 +49,12 @@ conversation labels feed the existing source guard before main-answer dispatch.
49
49
  Unsupported input fails explicitly, without Google or OpenAI inference fallback.
50
50
  No independent WebKit client or private WebKit SPI is included.
51
51
 
52
+ Antigravity reads one request settings snapshot for model selection and its Copilot header-wait budget, and reads source access at route selection. Response headers end the Copilot header-wait deadline. Streaming then uses its independent idle budget whether the header limit was saved explicitly or inherited. The Chat bridge aggregates reported usage fields once and feeds the same numeric fields to the client and ledger. Structured stream errors retain the actual HTTP status, safe failure type and validated retry guidance. No opened stream is replayed.
53
+
54
+ Antigravity keeps a bounded local conversation route table with keyed session hashes, hashed owners and model aliases. Compression consults the existing conversation owner guard before using the retained model. Unbound background tasks prefer Carbon Low and may use a compatible selected model from the same authorized source if it is unavailable. Copilot Chat recovery summaries require both a successful stop reason and the Chat stream terminator. The other protocols retain their own terminal contracts.
55
+
56
+ For managed GitHub Codex model plans, Auto Review resolves an explicit startup override within the authorized deployments before consulting saved or observed session routing. The saved effort is associated with its selected review route. A different override uses the app's requested effort, or Low when omitted and supported.
57
+
52
58
  ## Composition and lifecycle
53
59
 
54
60
  ### Application control and shared source admission
package/docs/REFERENCE.md CHANGED
@@ -24,7 +24,7 @@ For installation and first use, start with the [README](../README.md). This refe
24
24
  | `ccdx source github login` / `reauth` / `logout` | Manage the saved GitHub account |
25
25
  | `ccdx source m365 accounts` / `account` | List local company accounts or select one |
26
26
  | `ccdx app list` | Show client setup and observed activity |
27
- | `ccdx app <id> status [--details]` | Read client configuration and scoped features |
27
+ | `ccdx app <id> status` | Read client configuration and scoped features |
28
28
  | `ccdx app <id> models --edit` | Choose visible models and a default |
29
29
  | `ccdx app <id> sync --preview` | Preview the model/configuration plan |
30
30
  | `ccdx app <id> sync` | Write client settings owned by CCDX |
@@ -90,13 +90,13 @@ Choose its exposed models on the Antigravity page or with
90
90
  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.
91
91
  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.
92
92
 
93
- On the **Antigravity** page, set **Copilot response timeout (s)** to 1–600 seconds and save, or leave it blank to use the shared default. 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. Queue, request-body, stream idle, native Google, Codex and Claude limits do not change. If `CCDX_ANTIGRAVITY_COPILOT_TIMEOUT_MS` is set at startup, the page shows that value and disables editing.
93
+ On the **Antigravity** page, set **Copilot response-header timeout (s)** to 1–600 seconds and save, or leave it blank to use the shared default. 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.
94
94
 
95
95
  To use a custom Gemini API in Antigravity, add an API that declares **Gemini**. Its Gemini address is the versioned model-list URL, for example `https://generativelanguage.googleapis.com/v1beta/models`. Save an API key separately, read the model list, and save the desired Gemini deployments. In **Antigravity → Custom Gemini source**, choose the source and save. Its models appear in the client catalog alongside the existing models. Generation, streaming, and token counts use the selected source's Gemini API and key. CCDX does not send the App's Google credentials or switch an existing conversation to a different source. Reopen Antigravity only if the page shows a catalog reload is needed.
96
96
 
97
97
  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.
98
98
 
99
- Pausing Antigravity Copilot access retains its saved model selection. Native Google model routes remain available; Copilot models and all Antigravity background summaries, searches and images use Copilot. The connection indicator reports observed requests separately from enabled access, and connection activity includes discovery/control requests.
99
+ Pausing Antigravity Copilot access retains its saved model selection. Native Google model routes remain available; Copilot models, unbound summaries, searches and images use Copilot. Bound compression retains its source, model and advertised reasoning level. The connection indicator reports observed requests separately from enabled access, and connection activity includes discovery/control requests.
100
100
 
101
101
  The page distinguishes enabled access from an observed client connection.
102
102
 
@@ -106,7 +106,7 @@ before Copilot dispatch. Text, inline images and native function tools are
106
106
  converted to the advertised Copilot Chat interface; truncated streams report an
107
107
  error rather than successful completion.
108
108
 
109
- This Copilot selection does not restrict Antigravity's original Google model directory. Google wire IDs such as `gemini-3.8-flash-tiered` can therefore appear in usage without being CCDX-added model choices. The recorded provider distinguishes Google and GitHub Copilot; the ID alone does not establish a background task or a fallback. Known conversation compaction retains its observed source and model.
109
+ 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.
110
110
 
111
111
  `enable` saves CCDX settings and prepares its local source guard. `open --preview` shows the inspected application state without launching it.
112
112
  `open` starts a closed, verified Gemini App in `/Applications` or `~/Applications` with a process-local
@@ -135,7 +135,7 @@ Each protocol observer retains at most 64 series of 64 request points and 16 com
135
135
 
136
136
  ## Observed tool calls
137
137
 
138
- **Requests → Tool and agent activity** uses the existing activity stream for Codex, Claude and Antigravity. Assembly line is the default. It shows a roller belt feeding a press. You can also choose Beam ring, Grid or Off. This browser remembers valid choices; removed styles fall back to Assembly line. Captions change with observed call preparation, waiting and returned results. When no tools are pending, active conversation requests show processing or reply generation. These are observed gateway request phases, not a count of native subagents. Motion runs at a faster presentation cadence, independent of event frequency; it is not a progress percentage or a call counter. System reduced motion and hidden/off-screen views pause continuous drawing. Off stops drawing and keeps the status text. Returned results have at most a 0.9-second finish cue; failure, cancellation and unavailable evidence stop continuous motion.
138
+ **Requests → Tool and agent activity** offers Assembly line, Dual-lane sorter, Gantry transfer and Indexing table. Assembly line is the default and replaces removed preferences. 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.
139
139
 
140
140
  Calls are correlated using their IDs and the existing app/profile/session scope. A model emitting a tool call does not prove that the client executed it. Only a matching returned result ends the wait; ambiguous name-only Gemini results stay unconfirmed. Without a reliable session, completed requests show unconfirmed tool state. After 90 seconds without observable tool or response activity, the UI pauses and shows that fresh status is needed. Late results can update retained unconfirmed observations for another five minutes. These display deadlines never cancel tools or change source timeouts.
141
141
 
@@ -197,7 +197,7 @@ Model details can declare `max_tool_definitions` and `supported_parameters`. Cat
197
197
 
198
198
  HTTP failures retain a safe technical category, parameter path, reported numeric maximum, source, model, protocol and request ID when available. Unknown vendor explanations remain unknown. Default diagnostics do not copy vendor prose or prompts. HTTP 400 may be a parameter or context rejection; a count-endpoint 404 describes token counting separately.
199
199
 
200
- For an explicit one-shot investigation, run `ccdx requests diagnose --source ID --model ID --yes` on the running service. It captures the first matching Messages HTTP 400/422 within ten minutes, including a failure recovered by an existing compatibility retry. It retains at most 512 characters of redacted technical explanation in process memory; an explanation can still contain an unlabelled request fragment. No request body is saved and no model call is made. Read the result with `ccdx requests diagnose --format json`; clear or cancel it with `ccdx requests diagnose --cancel --yes`. Restarting clears the capture. A missing, oversized or slow error body produces `unavailable`; successful requests and other sources/models do not consume it. This diagnoses the rejection and does not change request parameters or prove the original problem is fixed.
200
+ For an explicit one-shot Messages HTTP 400 or 422 investigation, run `ccdx requests diagnose --source ID --model ID --yes` on the running service. It captures the first matching Messages HTTP 400/422 within ten minutes, including a failure recovered by an existing compatibility retry. It retains at most 512 characters of redacted technical explanation in process memory; an explanation can still contain an unlabelled request fragment. No request body is saved and no model call is made. Read the result with `ccdx requests diagnose --format json`; clear or cancel it with `ccdx requests diagnose --cancel --yes`. Restarting clears the capture. A missing, oversized or slow error body produces `unavailable`; successful requests and other sources/models do not consume it. This diagnoses the rejection and does not change request parameters or prove the original problem is fixed.
201
201
 
202
202
  Two confirmed connection failures or temporary 502/503/504 replies trigger a short cooldown for that source interface. The default delay is five seconds; a reported Retry-After can extend it to at most thirty seconds. One later real request checks recovery. Parameter/auth errors, missing token-count endpoints and client cancellation do not trigger it. Other sources and interfaces continue independently. There is no background paid probe or automatic model/account switch.
203
203
 
@@ -234,7 +234,8 @@ Catalog diagnostics distinguish local cached data from an online response and ex
234
234
  - **Saved account, access denied:** use source status/check to distinguish the saved credential from current access. `source github reauth` replaces sign-in only after a successful new login. Other apps' credentials are read-only.
235
235
  - **No client models:** inspect allowed sources, selected models and unavailable selections. An empty selection means paused access, not missing credentials.
236
236
  - **Configuration unchanged:** CCDX kept existing settings. Preview the intended plan before syncing; do not overwrite managed settings to force success.
237
- - **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.
237
+ - **Request failure:** use Requests or `ccdx requests --failed`. HTTP status and model outcome are separate. An HTTP 200 response can still report a stream failure. Token-count and access notices are visible in the unfiltered request list.
238
+ - **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`.
238
239
  - **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.
239
240
  - **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.
240
241
  - **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.
@@ -266,9 +267,9 @@ For an identified conversation, hovering a point in the input-history chart show
266
267
 
267
268
  ## Shared source concurrency
268
269
 
269
- In **Settings → Advanced: request limits**, **Shared request-body limit** sets the shared gateway reservation to 32–128 MiB (default 32 MiB). It applies at the next CCDX start. `ccdx config limits` shows the saved and running values. `CCDX_MAX_INFLIGHT_BODY_BYTES` still overrides the saved value. This control does not change per-request size limits, the decompressed-body or response-history pools, Claude's separate Messages queue, or provider concurrency. Increasing this limit does not fix a provider timeout. Antigravity control GETs without a framed body do not enter the upload queue. Allowlisted read-only control POSTs with a known, uncompressed body of at most 8 KiB use four independent slots and an eight-request waiting limit. Other requests still use the shared body queue. `ccdx status --json` reports the short queue under `gemini.activity.short_control_queue`.
270
+ In **Settings → Advanced: request limits**, **Shared request-body limit** sets the shared gateway reservation to 32–128 MiB (default 32 MiB). It applies at the next CCDX start. `ccdx config limits` shows the saved and running values. `CCDX_MAX_INFLIGHT_BODY_BYTES` still overrides the saved value. This control does not change per-request size limits, the decompressed-body or response-history pools, Claude's separate Messages queue, or provider concurrency. Increasing this limit does not fix a provider timeout. Antigravity control GETs without a framed body do not enter the upload queue. Allowlisted read-only control POSTs with a known, uncompressed body of at most 8 KiB use four independent slots and an eight-request waiting limit. Other requests still use the shared body queue. `ccdx status --details --format json` reports the short queue under `gemini.activity.short_control_queue`.
270
271
 
271
- `ccdx status` shows the longest admitted wait in the gateway's local request-body queue. `status --json` retains the longest sample and up to 16 recent waits, including cancellations and timeouts. Samples record a route, request ID, wait reason and byte counts in memory; no request body or credential is retained. The request table shows the total time. Its details keep source, input usage, and the separate phases. An open request detail in view retains its place as new records arrive. If its disclosure held keyboard focus, that focus is restored. In **Checks → Service requests**, the error category table separates generation, capability and access, request method, request path, and other errors. These classify the same errors shown in the 4xx/5xx totals. The existing request details distinguish local waiting from waiting for the selected source. Local waiting ends before the body is read, and source waiting ends before sending upstream. For Antigravity Copilot Chat, `ccdx status --json` reports how many body bytes were passed to the socket (`attempts[].body_written_bytes`), when the local send finished (`body_sent_ms`, measured from request receipt), the outbound client correlation ID (`client_request_id`), and any observed transport error (`transport_error`). The WebUI shows total duration, sending time, response-header wait and first usable output when available. Copy details keeps the local ID, outbound ID and upstream response ID distinct. Valid upstream retry guidance is preserved on 429 and 503; neither response triggers an automatic resend. A local timeout is not a recorded connection error. None of these markers prove the source received or processed the body.
272
+ `ccdx status --details` shows the longest admitted wait in the gateway's local request-body queue. `ccdx status --details --format json` retains the longest sample and up to 16 recent waits, including cancellations and timeouts. Samples record a route, request ID, wait reason and byte counts in memory; no request body or credential is retained. The request table shows the total time. Its details keep source, input usage, and the separate phases. An open request detail in view retains its place as new records arrive. If its disclosure held keyboard focus, that focus is restored. In **Checks → Service requests**, the error category table separates generation, capability and access, request method, request path, and other errors. These classify the same errors shown in the 4xx/5xx totals. The existing request details distinguish local waiting from waiting for the selected source. Local waiting ends before the body is read, and source waiting ends before sending upstream. For Antigravity Copilot Chat, `ccdx status --details --format json` reports how many body bytes were passed to the socket (`attempts[].body_written_bytes`), when the local send finished (`body_sent_ms`, measured from request receipt), the outbound client correlation ID (`client_request_id`), and any observed transport error (`transport_error`). The WebUI shows total duration, sending time, response-header wait and first usable output when available. Copy details keeps the local ID, outbound ID and upstream response ID distinct. Valid upstream retry guidance is preserved on 429 and 503; neither response triggers an automatic resend. A local timeout is not a recorded connection error. None of these markers prove the source received or processed the body.
272
273
 
273
274
  All three Apps share admission for the same configured source and account. A slot spans the real upstream response body through completion, cancellation or error. Request-body memory is tracked separately; uploads of unknown length start with a minimal reservation and grow it by bytes read, before retaining the data for parsing. If there is not enough room, reading pauses until existing requests release memory. Only one such reader per pool may grow at a time; a reader waiting for more memory takes priority over new admissions. Once upload is complete, another reader can start while the earlier request retains its actual body reservation. Requests larger than the pool still run exclusively at the pool ceiling, subject to the existing per-request limits. Growth waits share the existing upload deadline and can appear in the body-read time; the entry queue is recorded separately. Recovery and internal summaries acquire fresh slots after the rejected response releases its slot.
274
275
 
@@ -865,7 +866,7 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
865
866
  | `CCDX_DISABLE_USAGE` | unset | Set to `1` to disable usage logging |
866
867
  | `CCDX_SHUTDOWN_TIMEOUT_MS` | `5000` | Time to drain active HTTP connections before forcing shutdown |
867
868
 
868
- Antigravity starts the body deadline after queue admission. Its generation requests release body reservations after the final upstream response opens, while keeping response-restoration state until completion. Queue exhaustion or timeout returns `503`; a body timeout returns `408`; upstream and compaction timeouts return `504`. Client cancellation releases queued or active reservations. An HTTP success with no Copilot stream body returns `502` before CCDX opens its response stream.
869
+ Antigravity starts the body deadline after queue admission. One-shot Copilot generation releases request-body memory when the transport finishes writing it. Compression retains reusable input through recovery until the final response opens. Response restoration retains its own request state until completion. Queue exhaustion or timeout returns `503`; a body timeout returns `408`; upstream and compaction timeouts return `504`. Client cancellation releases queued or active reservations. An HTTP success with no Copilot stream body returns `502` before CCDX opens its response stream.
869
870
 
870
871
  ## Usage logging
871
872
 
@@ -893,7 +894,7 @@ Diagnostic redaction removes Basic authorization payloads and URL userinfo, and
893
894
 
894
895
  ## Debug logging
895
896
 
896
- Set `CCDX_LOG_PATH=1` to record diagnostic logs independently of quiet terminal presentation to `~/.local/share/codex-copilot-dx/debug.log`, or provide a custom path. Add `CCDX_LOG_LEVEL=debug` for upstream attempts, retry causes, status codes, and timings. The adapter does not deliberately dump request/response bodies or authorization headers. File diagnostics redact common credential forms and labelled content echoes, but this cannot identify every secret in arbitrary external prose; review logs before sharing them. File writes are asynchronous and batched with a 4096-record / 2 MiB pending-and-in-flight ceiling. Overflow drops excess file records with one warning and a status counter; terminal output continues. CLI exit paths flush for at most 1.5 seconds. `ccdx doctor config` bypasses file logging entirely.
897
+ Set `CCDX_LOG_PATH=1` to record diagnostic logs independently of quiet terminal presentation to `~/.local/share/codex-copilot-dx/debug.log`, or provide a custom path. Add `CCDX_LOG_LEVEL=debug` for upstream attempts, retry causes, status codes, and timings. The adapter does not deliberately dump request/response bodies or authorization headers. File diagnostics redact common credential forms and labelled content echoes, but this cannot identify every secret in arbitrary external prose; review logs before sharing them. Leave file diagnostics disabled for routine use. Use request details or a targeted one-shot capture before enabling debug logging. File writes are asynchronous and batched with a 4096-record / 2 MiB pending-and-in-flight ceiling. Overflow drops excess file records with one warning and a status counter; terminal output continues. CLI exit paths flush for at most 1.5 seconds. `ccdx doctor config` bypasses file logging entirely.
897
898
 
898
899
 
899
900
  ## Large histories and images
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.4.12",
3
+ "version": "1.4.13",
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",
@@ -20,6 +20,7 @@ const messages = {
20
20
  ccdx_api_model_unavailable: "This model is not configured for the requested API. Review the source's model list.",
21
21
  ccdx_api_environment_key_missing: "Set the configured API-key environment variable before starting CCDX.",
22
22
  ccdx_api_secret_unavailable: "The system credential store is unavailable. No plaintext fallback was used.",
23
+ ccdx_review_environment_override: "The startup setting CCDX_AUTO_REVIEW_MODEL controls the Auto Review model.",
23
24
  ccdx_client_source_mismatch: "Save the source before changing its review model.",
24
25
  };
25
26
  export const accessError = (code, statusCode = 400) => {
@@ -167,7 +167,33 @@ export function chatFunctionPart(call, originalNames) {
167
167
  return { functionCall: { id: call.id, name, args } };
168
168
  }
169
169
 
170
- export function chatToAntigravity(response, originalNames) {
170
+ const validCount = value => Number.isSafeInteger(value) && value >= 0;
171
+ export function mergeChatUsage(previous, value) {
172
+ if (!value || typeof value !== "object") return previous;
173
+ let next = previous;
174
+ for (const key of ["prompt_tokens", "completion_tokens", "total_tokens"]) {
175
+ if (validCount(value[key])) (next ||= {})[key] = value[key];
176
+ }
177
+ for (const [key, field] of [["prompt_tokens_details", "cached_tokens"], ["completion_tokens_details", "reasoning_tokens"]]) {
178
+ if (validCount(value[key]?.[field])) (next ||= {})[key] = { [field]: value[key][field] };
179
+ }
180
+ return next;
181
+ }
182
+
183
+ function geminiUsage(usage) {
184
+ if (!usage) return {};
185
+ const result = {}, reasoning = usage.completion_tokens_details?.reasoning_tokens;
186
+ const separateThinking = reasoning !== undefined && usage.completion_tokens !== undefined && reasoning <= usage.completion_tokens;
187
+ const candidates = separateThinking ? usage.completion_tokens - reasoning : usage.completion_tokens;
188
+ for (const [key, value] of [["promptTokenCount", usage.prompt_tokens], ["candidatesTokenCount", candidates],
189
+ ["totalTokenCount", usage.total_tokens], ["cachedContentTokenCount", usage.prompt_tokens_details?.cached_tokens],
190
+ ["thoughtsTokenCount", separateThinking ? reasoning : undefined]]) {
191
+ if (value !== undefined) result[key] = value;
192
+ }
193
+ return { usageMetadata: result };
194
+ }
195
+
196
+ export function chatToAntigravity(response, originalNames, usage = mergeChatUsage(null, response?.usage)) {
171
197
  const choice = response?.choices?.[0], message = choice?.message;
172
198
  if (!object(message)) throw invalid("Invalid upstream Chat response", 502);
173
199
  const parts = [];
@@ -176,12 +202,11 @@ export function chatToAntigravity(response, originalNames) {
176
202
  if (Array.isArray(message.tool_calls)) for (const call of message.tool_calls) parts.push(chatFunctionPart(call, originalNames));
177
203
  const finish = { stop: "STOP", tool_calls: "STOP", length: "MAX_TOKENS", content_filter: "SAFETY" }[choice.finish_reason];
178
204
  if (!finish || finish === "STOP" && !parts.some(part => !part.thought)) throw invalid("Upstream Chat response did not complete", 502);
179
- const usage = response.usage;
180
205
  return { candidates: [{ content: { role: "model", parts }, finishReason: finish, index: 0 }],
181
- ...(usage ? { usageMetadata: { promptTokenCount: usage.prompt_tokens || 0, candidatesTokenCount: usage.completion_tokens || 0, totalTokenCount: usage.total_tokens || 0 } } : {}) };
206
+ ...geminiUsage(usage) };
182
207
  }
183
208
 
184
- export async function* chatStreamToAntigravity(response, originalNames, { onChunk, onUsage } = {}) {
209
+ export async function* chatStreamToAntigravity(response, originalNames, { onChunk, onUsage, onError } = {}) {
185
210
  if (!response?.body) throw invalid("Upstream Chat stream has no body", 502);
186
211
  const calls = new Map(), data = [], guard = new ToolArgumentDeltaGuard();let done = false, finish = null, usage = null, bytes = 0, visible = false;
187
212
  const frame = async function* () {
@@ -189,9 +214,14 @@ export async function* chatStreamToAntigravity(response, originalNames, { onChun
189
214
  const raw = data.join("\n");data.length = 0;
190
215
  if (raw === "[DONE]") { done = true;return; }
191
216
  let event;try { event = JSON.parse(raw); } catch { throw invalid("Invalid upstream Chat stream event", 502); }
192
- const upstreamError = upstreamChatStreamError(event);if (upstreamError) { observeSourceStreamFailure(response, event.error);throw upstreamError; }
193
- if (event?.usage) usage = event.usage;
194
- if (event?.usage || event?.copilot_usage) onUsage?.(event);
217
+ if (event?.usage) usage = mergeChatUsage(usage, event.usage);
218
+ if (event?.usage || event?.copilot_usage) onUsage?.(event, usage);
219
+ const upstreamError = upstreamChatStreamError(event);
220
+ if (upstreamError) {
221
+ observeSourceStreamFailure(response, event.error);
222
+ onError?.(upstreamError, event.error);
223
+ throw upstreamError;
224
+ }
195
225
  const choice = event?.choices?.[0];
196
226
  if (!choice) return;
197
227
  if (choice.finish_reason) { finish = choice.finish_reason;sourceResponseAccepted(response); }
@@ -240,5 +270,5 @@ export async function* chatStreamToAntigravity(response, originalNames, { onChun
240
270
  yield { response: { candidates: [{ index: 0, content: { role: "model", parts: [chatFunctionPart(call, originalNames)] } }] } };
241
271
  }
242
272
  yield { response: { candidates: [{ index: 0, finishReason }],
243
- ...(usage ? { usageMetadata: { promptTokenCount: usage.prompt_tokens || 0, candidatesTokenCount: usage.completion_tokens || 0, totalTokenCount: usage.total_tokens || 0 } } : {}) } };
273
+ ...geminiUsage(usage) } };
244
274
  }
@@ -4,13 +4,14 @@ import {buildResponsesUsageRecord,recordUsage} from "./usage-store.mjs";
4
4
  import {createRequestAbort,abortErrorStatusCode,readJsonBody,readBoundedResponseText,writeOrDrain,httpError,sendJsonError,sendUpstreamError} from "./http-transport.mjs";
5
5
  import {safeUpstreamResponseHeaders,upstreamRejectionHeaders} from "./upstream-headers.mjs";
6
6
  import {isLoopbackAddress,isLoopbackHostHeader} from "./security.mjs";
7
- import {antigravityToChat,chatToAntigravity,chatStreamToAntigravity,parseAntigravityJSON} from "./antigravity-chat-bridge.mjs";
7
+ import {antigravityToChat,chatToAntigravity,chatStreamToAntigravity,mergeChatUsage,parseAntigravityJSON} from "./antigravity-chat-bridge.mjs";
8
8
  import {ANTIGRAVITY_MODEL_PREFIX,ANTIGRAVITY_NATIVE_PREFIX,antigravityCopilotModels,hasAntigravityAgentDefault,mergeAntigravityModels} from "./antigravity-models.mjs";
9
9
  import {createPrivacyTextFragments} from "./privacy-stream.mjs";
10
10
  import {createGoogleResponseObserver,googleUsageEvent} from "./antigravity-usage.mjs";
11
11
  import {currentRequestContext,observeRequestedModel} from "./request-context.mjs";
12
12
  import {measureRequestStageAsync,markUpstreamStarted,markUpstreamHeaders,markFirstOutput,markOutputTokens,markRequestObservation,markResponseModel,markResponseErrorOrigin,markResponseTerminal,markToolActivity} from "./stream-performance.mjs";
13
13
  import {isCompactionRequest} from "./context-compaction.mjs";
14
+ import {safeUpstreamReason} from "./safe-upstream-error.mjs";
14
15
  import {compactionSummarizer} from "./context-compaction-wire.mjs";
15
16
  import {requestPurpose} from "./request-context.mjs";
16
17
  import {observeContextSession} from "./context-metrics.mjs";
@@ -45,7 +46,7 @@ function groundedSearch(result,query){
45
46
  export function createAntigravityHandler({client,models=()=>[],selectedModels=()=>null,defaultModel=()=>null,enabled=()=>false,privacy,searchFn,imageFn,guardSource,acquireRequest=async()=>()=>{},sourceAdmission,applicationEvidence,
46
47
  nativeModels=()=>[],resolveNativeModel=()=>null,
47
48
  compaction,compactionProfile=()=>"github",rememberConversationSource=()=>{},resolveCompactionSource=()=>null,recordUsageFn=recordUsage,fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,copilotTimeoutMs,streamIdleTimeoutMs=60000,
48
- generationSettings=()=>({ selection:selectedModels(), copilotTimeoutMs })}={}) {
49
+ requestSettings,generationSettings=()=>({ selection:selectedModels(), copilotTimeoutMs, preferred:defaultModel() })}={}) {
49
50
  if(![GOOGLE_ORIGIN,"https://cloudcode-pa.googleapis.com"].includes(googleOrigin))throw new Error("Unrecognized Google control origin");
50
51
  const acquireControl=createRequestAdmission({maxBytes:4*CONTROL_BODY_BYTES,maxQueued:8});
51
52
  let active=0,observed=false,catalogModels=null,catalogDefaultSupported=null,catalogDefaultModel=null;const nativeWindows=new Map();
@@ -56,11 +57,9 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
56
57
  body=null;request=null;if(converted)converted.chat=null;if(session)session.body=null;
57
58
  const done=release;release=()=>{};done();
58
59
  };
59
- const captureUsage=event=>{
60
+ const captureUsage=(event,usage=mergeChatUsage(null,event?.usage))=>{
60
61
  if(!event?.usage&&!event?.copilot_usage)return;
61
- const known=value=>Number.isSafeInteger(value)&&value>=0,u={...usageEvent?.usage},incoming=event.usage;
62
- for(const key of ["prompt_tokens","completion_tokens","total_tokens"])if(known(incoming?.[key]))u[key]=incoming[key];
63
- 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]};
62
+ const known=value=>Number.isSafeInteger(value)&&value>=0,u=usage||{};
64
63
  const billing=Array.isArray(event.copilot_usage?.token_details)?event.copilot_usage:undefined;
65
64
  usageEvent={...usageEvent,...(Object.keys(u).length?{usage:u}:{}),...(billing?{copilot_usage:billing}:{}),
66
65
  ...(typeof event.id==="string"?{id:event.id}:{}),...(typeof event.model==="string"?{model:event.model}:{})};
@@ -72,8 +71,9 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
72
71
  };
73
72
  active++;counts.total++;
74
73
  try{
75
- if(!enabled())throw httpError("Antigravity integration is disabled",503);
76
74
  if(!isLoopbackAddress(req.socket?.remoteAddress)||!isLoopbackHostHeader(req.headers.host)||Object.hasOwn(req.headers,"origin"))throw httpError("Antigravity requires a native local client",403);
75
+ const config=requestSettings?.();
76
+ if(!enabled(config))throw httpError("Antigravity integration is disabled",503);
77
77
  if(!["POST","GET"].includes(req.method))throw httpError("Unsupported Antigravity method",405);
78
78
  const local=new URL(req.url,"http://localhost"),route=local.pathname.slice(PREFIX.length);
79
79
  const match=/^\/v1internal(?::|\/)([A-Za-z][A-Za-z0-9]*)$/.exec(route);
@@ -99,7 +99,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
99
99
  if(compacting&&context){context.purpose=requestPurpose(req.headers["x-ccdx-purpose"],"compaction");context.streamPerformance?.setPurpose(context.purpose)}
100
100
  if(compacting)markRequestObservation({compaction:1});
101
101
  if(body?.model)observeRequestedModel(body);
102
- const compactBinding=compacting?await resolveCompactionSource(body):null;
102
+ const compactBinding=compacting?await resolveCompactionSource(body,config):null;
103
103
  if(compactBinding?.model)body={...body,model:compactBinding.model};
104
104
  markRequestObservation({requested_model:context?.requestedModel});
105
105
  abort.setTimeout(upstreamTimeoutMs,"upstream_timeout");
@@ -134,7 +134,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
134
134
  if(method==="fetchAvailableModels"&&upstream.ok){
135
135
  const value=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:8*1024*1024,signal:abort.signal,label:"Google model catalog"}));
136
136
  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)}
137
- const merged=mergeAntigravityModels(value,models(),selectedModels(),defaultModel(),nativeModels());
137
+ const merged=mergeAntigravityModels(value,models(config),selectedModels(config),defaultModel(config),nativeModels(config));
138
138
  catalogDefaultSupported=hasAntigravityAgentDefault(value);
139
139
  catalogDefaultModel=catalogDefaultSupported&&merged.defaultAgentModelId.startsWith(ANTIGRAVITY_MODEL_PREFIX)?merged.defaultAgentModelId:null;
140
140
  catalogModels=Object.keys(merged.models).filter(id=>id.startsWith(ANTIGRAVITY_MODEL_PREFIX)||id.startsWith(ANTIGRAVITY_NATIVE_PREFIX));
@@ -171,7 +171,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
171
171
  res.end();
172
172
  };
173
173
  if(method==="countTokens"&&req.method==="POST"&&typeof body?.model==="string"&&body.model.startsWith(ANTIGRAVITY_NATIVE_PREFIX)){
174
- const selected=resolveNativeModel(body.model);
174
+ const selected=resolveNativeModel(body.model,config);
175
175
  if(!selected)throw httpError("The selected Gemini source is unavailable",503);
176
176
  if(!body.request)throw httpError("Invalid Gemini token count request",400);
177
177
  if(body.request.labels?.root_cascade_id||body.request.labels?.cascade_id)await guardSource?.(body,selected.source,abort.signal);
@@ -195,13 +195,13 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
195
195
  observed=true;return await native();
196
196
  }
197
197
  if(req.method!=="POST"||!body||typeof body.model!=="string"||!body.request)throw httpError("Invalid Antigravity generation request",400);
198
- const { selection, copilotTimeoutMs:requestCopilotTimeoutMs }=generationSettings();
198
+ const { selection, copilotTimeoutMs:requestCopilotTimeoutMs, preferred }=generationSettings(config);
199
199
  if(body.model.startsWith(ANTIGRAVITY_NATIVE_PREFIX)){
200
- const selected=resolveNativeModel(body.model);
200
+ const selected=resolveNativeModel(body.model,config);
201
201
  if(!selected)throw httpError("The selected Gemini source is unavailable",503);
202
202
  if(!["agent","checkpoint","summarization","title"].includes(body.requestType))throw httpError("Unsupported native Gemini request type",400);
203
- await guardSource?.(body,selected.source,abort.signal);
204
- if(body.requestType==="agent")rememberConversationSource(body,selected.source);
203
+ const profile=await guardSource?.(body,selected.source,abort.signal);
204
+ if(body.requestType==="agent")await rememberConversationSource(body,selected.source,abort.signal,profile);
205
205
  const stream=method==="streamGenerateContent",source=selected.transport;
206
206
  usageProvider=selected.source;usageModel=selected.model;usageMode=stream?"sse":"json";
207
207
  if(context){context.provider=selected.source;context.streamPerformance?.setProvider?.(selected.source)}
@@ -266,15 +266,16 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
266
266
  }catch(error){sourceResponseFailed(upstream);await cancelSourceResponse(upstream).catch(()=>{});markResponseErrorOrigin("upstream_event");throw error;}
267
267
  return;
268
268
  }
269
- const copilotModels=antigravityCopilotModels(models()),selected=copilotModels.find(model=>model.id===body.model&&(selection===null||selection.includes(model.id)));
269
+ const copilotModels=antigravityCopilotModels(models(config)),selected=copilotModels.find(model=>model.id===body.model&&(selection===null||selection.includes(model.id)));
270
270
  if((body.requestType==="agent"||compactBinding?.source==="google")&&!selected){
271
271
  if(body.model.startsWith(ANTIGRAVITY_MODEL_PREFIX))throw httpError("The selected Copilot model is unavailable",503);
272
- if(body.requestType==="agent"||body.request?.labels?.root_cascade_id||body.request?.labels?.cascade_id)await guardSource?.(body,"google",abort.signal);
273
- if(body.requestType==="agent")rememberConversationSource(body,"google");
272
+ const hasSession=body.requestType==="agent"||body.request?.labels?.root_cascade_id||body.request?.labels?.cascade_id;
273
+ const profile=hasSession?await guardSource?.(body,"google",abort.signal):undefined;
274
+ if(body.requestType==="agent")await rememberConversationSource(body,"google",abort.signal,profile);
274
275
  return await native();
275
276
  }
276
- if(body.requestType==="agent"||compactBinding?.source==="github")await guardSource?.(body,"github",abort.signal);
277
- if(body.requestType==="agent")rememberConversationSource(body,"github");
277
+ const profile=body.requestType==="agent"||compactBinding?.source==="github"
278
+ ?await guardSource?.(body,"github",abort.signal):undefined;
278
279
  if(!copilotModels.length)throw httpError("Copilot access for Antigravity is paused or unavailable",503);
279
280
  observed=true;counts.copilot++;
280
281
  if(context){context.provider="github";context.streamPerformance?.setProvider?.("github")}
@@ -298,11 +299,21 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
298
299
  res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response}));return;
299
300
  }
300
301
  if(!["agent","checkpoint","summarization","title"].includes(body.requestType))throw httpError("Unsupported Antigravity inference type",400);
301
- const target=body.requestType==="agent"||compactBinding&&!compactBinding.background?selected:copilotModels.find(model=>model.model==="gemini-4-carbon"&&model.effort==="low");
302
- if(!target)throw httpError("Copilot Carbon is unavailable for Antigravity background tasks",503);
302
+ const bound=body.requestType==="agent"||compactBinding&&!compactBinding.background;
303
+ let target=selected;
304
+ if(!bound){
305
+ target=copilotModels.find(model=>model.model==="gemini-4-carbon"&&model.effort==="low");
306
+ if(!target){
307
+ const eligible=copilotModels.filter(model=>selection===null||selection.includes(model.id));
308
+ target=eligible.find(model=>model.id===preferred)||eligible.find(model=>model.effort==="low")||eligible[0];
309
+ }
310
+ }
311
+ if(!target)throw httpError(bound?"The conversation model is unavailable for Antigravity":"No eligible Copilot model is available for Antigravity background tasks",503);
312
+ if(body.requestType==="agent")await rememberConversationSource(body,"github",abort.signal,profile);
303
313
  const stream=method==="streamGenerateContent";usageModel=target.model;usageMode=stream?"sse":"json";usageProvider="github";
304
314
  converted=antigravityToChat(request,{model:target.model,effort:target.effort,reasoningEfforts:target.effort?[target.effort]:[],stream});
305
- markResponseModel(target.model);markRequestObservation({usage_state:"pending",context_window_tokens:target.maxTokens});
315
+ markResponseModel(target.model);markRequestObservation({usage_state:"pending",context_window_tokens:target.maxTokens,
316
+ routing_reason:bound?"conversation_model":target.model==="gemini-4-carbon"&&target.effort==="low"?"background_default":"background_available"});
306
317
  session=privacy?.prepareSession?await privacy.prepareSession(converted.chat,{protocol:"chat",client:"gemini",signal:abort.signal}):passthrough(converted.chat);
307
318
  const callOptions={signal:abort.signal,sourceBodyManaged:true,observeBodyWrite:true,retryOptions:{retries:0},
308
319
  ...(compacting?{}:{onBodySent:releaseInput}),
@@ -310,7 +321,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
310
321
  phase="upstream";
311
322
  const upstream=compacting&&compaction?await compaction.run({body:session.body,protocol:"chat",scope:JSON.stringify(["gemini","github",compactionProfile()]),source:"github",client:"gemini",
312
323
  inputLimit:target.maxTokens,outputAllowance:session.body.max_completion_tokens||session.body.max_tokens||0,native:client.chatCompletions,options:callOptions,
313
- summarize:compactionSummarizer(session.body,"chat",client.chatCompletions),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await client.chatCompletions(session.body,callOptions);
324
+ summarize:compactionSummarizer(session.body,"chat",client.chatCompletions,{requireChatDone:true}),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await client.chatCompletions(session.body,callOptions);
314
325
  releaseInput();
315
326
  markUpstreamHeaders(upstream.status);
316
327
  applicationEvidence?.accept(req,"antigravity","inference");
@@ -320,10 +331,11 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
320
331
  abort.signal.throwIfAborted();counts.failed++;outcome="failed";markResponseTerminal(outcome,{origin:"upstream_http"});
321
332
  sendUpstreamError(res,{status,headers},JSON.stringify({error:"Copilot generation was refused (HTTP "+status+")"}));return;
322
333
  }
323
- if(requestCopilotTimeoutMs!==undefined)abort.setTimeout(stream?streamIdleTimeoutMs:upstreamTimeoutMs,stream?"stream_idle_timeout":"upstream_timeout");
334
+ abort.setTimeout(stream?streamIdleTimeoutMs:upstreamTimeoutMs,stream?"stream_idle_timeout":"upstream_timeout");
324
335
  if(!stream){
325
- const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));captureUsage(data);
326
- const result=chatToAntigravity(data,converted.originalNames);markToolActivity(result,"gemini");
336
+ const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));
337
+ const usage=mergeChatUsage(null,data.usage);captureUsage(data,usage);
338
+ const result=chatToAntigravity(data,converted.originalNames,usage);markToolActivity(result,"gemini");
327
339
  outcome=result.candidates[0].finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome);
328
340
  res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response:session.restoreValue(result)}));return;
329
341
  }
@@ -335,7 +347,14 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
335
347
  const text=session.count?createPrivacyTextFragments(session):{push:value=>value,finish:()=>""};
336
348
  res.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache"});
337
349
  const emit=chunk=>writeOrDrain(res,"data: "+JSON.stringify(chunk)+"\n\n",{signal:abort.signal});
338
- for await(const chunk of chatStreamToAntigravity(upstream,converted.originalNames,{onChunk:()=>abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout"),onUsage:captureUsage})){
350
+ for await(const chunk of chatStreamToAntigravity(upstream,converted.originalNames,{onChunk:()=>abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout"),onUsage:captureUsage,onError:(error,detail)=>{
351
+ markResponseErrorOrigin("upstream_event");
352
+ const reason=safeUpstreamReason(detail?.code,200,{stream:true})||safeUpstreamReason(detail?.type,200,{stream:true});
353
+ const headers=upstream.headers;
354
+ currentRequestContext()?.onHttpError?.({code:error.code,origin:"upstream_event",model_error:true,headers,
355
+ ...(reason?{upstream_code:reason.code}:{})});
356
+ error.message=reason?.message||"The model source reported an error while streaming.";
357
+ }})){
339
358
  markToolActivity(chunk,"gemini");
340
359
  const candidate=chunk.response?.candidates?.[0];
341
360
  for(const part of candidate?.content?.parts||[]){
@@ -357,6 +376,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
357
376
  if(!cancelled||!["completed","incomplete"].includes(outcome))outcome=cancelled?"cancelled":"failed";
358
377
  const origin=outcome==="cancelled"?"client_disconnect":currentRequestContext()?.errorOrigin||(abort.reason||phase==="admission"?"transport":["privacy","source_admission"].includes(error.origin)?error.origin:error.statusCode<500?"client_validation":"transport");
359
378
  markResponseErrorOrigin(origin);markResponseTerminal(outcome,{origin});
379
+ if(res.headersSent&&outcome==="failed"&&abort.reason)currentRequestContext()?.onHttpError?.({code:error.code,origin,model_error:true});
360
380
  if(res.headersSent&&!res.writableEnded&&!res.destroyed){res.end("data: "+JSON.stringify({error:{code:error.statusCode||502,message:error.message}})+"\n\n");}
361
381
  else sendJsonError(res,error,error.statusCode||502);
362
382
  }finally{
@@ -375,9 +395,9 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
375
395
  }
376
396
  }
377
397
  };
378
- handler.snapshot=()=>{
398
+ handler.snapshot=(config)=>{
379
399
  const queue=acquireControl.diagnostics();
380
- return {enabled:enabled(),observed,catalog_models:catalogModels,catalog_default_supported:catalogDefaultSupported,catalog_default_model:catalogDefaultModel,active,...counts,
400
+ return {enabled:enabled(config),observed,catalog_models:catalogModels,catalog_default_supported:catalogDefaultSupported,catalog_default_model:catalogDefaultModel,active,...counts,
381
401
  short_control_queue:{active:queue.activeRequests,waiting:queue.queued,queued_total:queue.queuedTotal,rejected:queue.rejected,timed_out:queue.timedOut,wait_ms_max:queue.waitMsMax}};
382
402
  };
383
403
  return handler;