codex-copilot-dx 1.4.11 → 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 +3 -3
- package/bin/cli.mjs +2 -0
- package/docs/ARCHITECTURE.md +6 -0
- package/docs/REFERENCE.md +21 -10
- package/package.json +1 -1
- package/src/access-settings.mjs +4 -1
- package/src/adapter.mjs +14 -5
- package/src/antigravity-chat-bridge.mjs +38 -8
- package/src/antigravity-handler.mjs +141 -26
- package/src/antigravity-models.mjs +3 -2
- package/src/antigravity-runtime.mjs +129 -36
- package/src/antigravity-usage.mjs +3 -3
- package/src/api-target.mjs +12 -1
- package/src/application-configuration.mjs +2 -1
- package/src/application-control.mjs +6 -3
- package/src/cli-command-spec.mjs +1 -1
- package/src/cli-management.mjs +9 -4
- package/src/connection-management.mjs +6 -2
- package/src/connection-policy.mjs +3 -3
- package/src/connection-routing.mjs +37 -10
- package/src/connection-runtime.mjs +4 -0
- package/src/connection-view.mjs +12 -0
- package/src/context-compaction-wire.mjs +6 -6
- package/src/copilot-client.mjs +3 -2
- package/src/copilot.mjs +13 -2
- package/src/dashboard/connections.js +18 -8
- package/src/dashboard/console.js +9 -4
- package/src/dashboard/context.js +15 -5
- package/src/dashboard/features.js +2 -2
- package/src/dashboard/flow.js +1 -0
- package/src/dashboard/gemini.js +40 -10
- package/src/dashboard/index.html +47 -40
- package/src/dashboard/language.js +44 -16
- package/src/dashboard/status.js +35 -30
- package/src/dashboard/tool-activity-machines.js +362 -0
- package/src/dashboard/tool-activity.js +24 -115
- package/src/dashboard/tools.js +3 -4
- package/src/dashboard/ui.css +44 -14
- package/src/dashboard/ui.js +14 -0
- package/src/dashboard/usage.js +9 -1
- package/src/dashboard.mjs +1 -0
- package/src/failure-history.mjs +97 -0
- package/src/model-capabilities.mjs +1 -1
- package/src/privacy-transform.mjs +22 -4
- package/src/provider-metadata.mjs +1 -1
- package/src/providers/api-network.mjs +4 -3
- package/src/providers/api.mjs +79 -15
- package/src/response-failures.mjs +10 -4
- package/src/runtime-config.mjs +1 -0
- package/src/safe-upstream-error.mjs +2 -2
- package/src/source-admission.mjs +1 -1
- package/src/stream-performance.mjs +1 -1
- package/src/terminal-state.mjs +8 -2
- package/src/windows-http-network.mjs +4 -3
- package/src/windows-prediction-network.cs +11 -0
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
|
|
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
|
|
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
|
|
package/bin/cli.mjs
CHANGED
|
@@ -279,6 +279,7 @@ const { startAdapter } = await import("../src/adapter.mjs");
|
|
|
279
279
|
const { defaultCopilotClient, refreshVSCodeVersion } = await import("../src/copilot.mjs");
|
|
280
280
|
const { configureLogging } = await import("../src/log.mjs");
|
|
281
281
|
const { flushUsageWrites } = await import("../src/usage.mjs");
|
|
282
|
+
const { failureHistoryPath } = await import("../src/failure-history.mjs");
|
|
282
283
|
const { runDoctor } = await import("../src/doctor.mjs");
|
|
283
284
|
const { adapterBaseUrl, checkRunningAdapter } = await import("../src/running-adapter.mjs");
|
|
284
285
|
const { assertSafeAdapterHost, isLoopbackHost } = await import("../src/security.mjs");
|
|
@@ -533,6 +534,7 @@ try {
|
|
|
533
534
|
const codexModelCatalog = createCodexModelCatalog();
|
|
534
535
|
activeServer = await startAdapter(serviceWorker?.warming ? 0 : ADAPTER_PORT, serviceWorker?.warming ? "127.0.0.1" : ADAPTER_HOST, {
|
|
535
536
|
log: startupLogger("Service"),
|
|
537
|
+
failureHistoryFile: process.env.CCDX_DISABLE_USAGE === "1" ? undefined : failureHistoryPath(),
|
|
536
538
|
autoReviewModelResolver: () => autoReviewPreference(),
|
|
537
539
|
codexClient: providerRuntime.source("github").client,
|
|
538
540
|
codexModelCatalog,
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -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
|
|
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 |
|
|
@@ -68,6 +68,9 @@ An app model file contains `deployments: [{"source":"github","model":"<model-id>
|
|
|
68
68
|
|
|
69
69
|
Claude App deployments may also specify `reasoning_effort`, for example `{"source":"api_work","model":"reasoner","reasoning_effort":"xhigh"}`. Omit it to follow the App. A client can send an automatic level even without a visible selection; CCDX preserves that supplied value. The fallback applies only when the request omits the field. `app claude-app models --edit` and the TUI expose the source's declared choices for models needing CCDX control, and preserve existing defaults during other model edits. This preference belongs to that client's source/model binding, not to the source shared with Codex or Claude Code.
|
|
70
70
|
|
|
71
|
+
In **Codex → Auto review**, **Save review settings** keeps the selected model and thinking level across CCDX restarts. For a managed GitHub model plan, the page reads the saved Codex binding. This setting does not change the conversation model.
|
|
72
|
+
Choose **Follow conversation model** to use an observed model from the same Codex session, with the managed default as a fallback. CCDX fills in `low` when the request omitted its effort and the selected model declares support. A saved explicit review model stays pinned.
|
|
73
|
+
|
|
71
74
|
## Antigravity in Gemini App
|
|
72
75
|
|
|
73
76
|
The **Antigravity** page and `ccdx app antigravity status|models|enable|disable|open`
|
|
@@ -87,9 +90,13 @@ Choose its exposed models on the Antigravity page or with
|
|
|
87
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.
|
|
88
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.
|
|
89
92
|
|
|
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
|
+
|
|
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
|
+
|
|
90
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.
|
|
91
98
|
|
|
92
|
-
Pausing Antigravity Copilot access retains its saved model selection. Native Google model routes remain available; Copilot models
|
|
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.
|
|
93
100
|
|
|
94
101
|
The page distinguishes enabled access from an observed client connection.
|
|
95
102
|
|
|
@@ -99,7 +106,7 @@ before Copilot dispatch. Text, inline images and native function tools are
|
|
|
99
106
|
converted to the advertised Copilot Chat interface; truncated streams report an
|
|
100
107
|
error rather than successful completion.
|
|
101
108
|
|
|
102
|
-
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
|
|
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.
|
|
103
110
|
|
|
104
111
|
`enable` saves CCDX settings and prepares its local source guard. `open --preview` shows the inspected application state without launching it.
|
|
105
112
|
`open` starts a closed, verified Gemini App in `/Applications` or `~/Applications` with a process-local
|
|
@@ -128,7 +135,7 @@ Each protocol observer retains at most 64 series of 64 request points and 16 com
|
|
|
128
135
|
|
|
129
136
|
## Observed tool calls
|
|
130
137
|
|
|
131
|
-
**Requests → Tool and agent activity**
|
|
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.
|
|
132
139
|
|
|
133
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.
|
|
134
141
|
|
|
@@ -190,7 +197,7 @@ Model details can declare `max_tool_definitions` and `supported_parameters`. Cat
|
|
|
190
197
|
|
|
191
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.
|
|
192
199
|
|
|
193
|
-
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.
|
|
194
201
|
|
|
195
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.
|
|
196
203
|
|
|
@@ -202,6 +209,8 @@ New requests accept the explicit local `X-CCDX-Purpose` value `conversation`, `c
|
|
|
202
209
|
|
|
203
210
|
Applications retain their native compression triggers. Codex uses `/v1/responses/compact` or its terminal `compaction_trigger` on Responses; Claude uses its explicit `x-claude-code-request-class: compaction` hint; Antigravity uses `summarization` and `checkpoint` request types. Claude synchronization enables its supported native gateway hint headers through owned settings. Existing running clients may need a normal reopen to adopt that environment setting; CCDX never force-restarts an App and never detects compaction by reading prompt wording.
|
|
204
211
|
|
|
212
|
+
Codex also reduces large Responses uploads by optimizing screenshots and managing materialized history. That path is specific to the Responses contract. Claude and Antigravity use the shared summary recovery described here; they do not have their tool results or signed state stripped by Codex's upload optimization.
|
|
213
|
+
|
|
205
214
|
Native compression is tried first. A missing Responses compact operation or a confirmed source input-length rejection can enter bounded recovery using the same authorized source, model and reasoning controls. Authentication, quota and unrelated parameter failures do not trigger recovery. Actual unsupported-endpoint observations are scoped to the source connection and model and expire after one minute. Unknown input windows remain unknown; a source-reported limit bounds a stale larger declaration. No paid discovery probes run.
|
|
206
215
|
|
|
207
216
|
Recovery preserves human messages, system instructions, tool declarations, signed/opaque state, and unfinished tool pairs. Only completed eligible historical assistant/tool records are summarized. Up to four UTF-8-sized segments and one merge job are allowed, followed by at most one retry of the original Messages/Chat/Gemini compression request. Segment sizing is a byte-based work bound, not a claimed exact token count. Recovery has a five-minute deadline and at most two concurrent gateway recoveries. An unknown window, protected-only history, oversized workload, incomplete summary or repeated rejection fails explicitly while keeping the original conversation. There is no recursive recovery or automatic source/account/model switch. Gateway recovery handles pre-output HTTP rejections; an already-started source stream is never replayed.
|
|
@@ -225,7 +234,8 @@ Catalog diagnostics distinguish local cached data from an online response and ex
|
|
|
225
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.
|
|
226
235
|
- **No client models:** inspect allowed sources, selected models and unavailable selections. An empty selection means paused access, not missing credentials.
|
|
227
236
|
- **Configuration unchanged:** CCDX kept existing settings. Preview the intended plan before syncing; do not overwrite managed settings to force success.
|
|
228
|
-
- **Request failure:** use Requests or `ccdx requests --failed`. HTTP
|
|
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`.
|
|
229
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.
|
|
230
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.
|
|
231
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.
|
|
@@ -257,9 +267,9 @@ For an identified conversation, hovering a point in the input-history chart show
|
|
|
257
267
|
|
|
258
268
|
## Shared source concurrency
|
|
259
269
|
|
|
260
|
-
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`.
|
|
261
271
|
|
|
262
|
-
`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.
|
|
263
273
|
|
|
264
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.
|
|
265
275
|
|
|
@@ -820,6 +830,7 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
|
|
|
820
830
|
| `CCDX_MAX_UPSTREAM_BODY_BYTES` | `31457280` | Strict maximum forwarded Responses body size; larger payloads are adapted locally or rejected with `413` |
|
|
821
831
|
| `CCDX_MAX_SSE_BUFFER_BYTES` | `8388608` | Maximum buffered bytes for one unterminated upstream SSE line or event |
|
|
822
832
|
| `CCDX_UPSTREAM_TIMEOUT_MS` | `120000` | Per-phase timeout for Responses/Messages preparation and non-streaming upstream requests |
|
|
833
|
+
| `CCDX_ANTIGRAVITY_COPILOT_TIMEOUT_MS` | `unset` | Startup override for Antigravity Copilot generation through response headers. If unset, use the saved value or the shared timeout. |
|
|
823
834
|
| `CCDX_STREAM_HANDSHAKE_TIMEOUT_MS` | `120000` | Timeout while waiting for upstream streaming response headers |
|
|
824
835
|
| `CCDX_STREAM_IDLE_TIMEOUT_MS` | `120000` | Maximum idle time between upstream streaming body chunks |
|
|
825
836
|
| `CCDX_UPSTREAM_RETRIES` | `2` | Retries for safe requests and clearly pre-connect POST failures; capped at `5` |
|
|
@@ -855,7 +866,7 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
|
|
|
855
866
|
| `CCDX_DISABLE_USAGE` | unset | Set to `1` to disable usage logging |
|
|
856
867
|
| `CCDX_SHUTDOWN_TIMEOUT_MS` | `5000` | Time to drain active HTTP connections before forcing shutdown |
|
|
857
868
|
|
|
858
|
-
Antigravity starts the body deadline after queue admission.
|
|
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.
|
|
859
870
|
|
|
860
871
|
## Usage logging
|
|
861
872
|
|
|
@@ -883,7 +894,7 @@ Diagnostic redaction removes Basic authorization payloads and URL userinfo, and
|
|
|
883
894
|
|
|
884
895
|
## Debug logging
|
|
885
896
|
|
|
886
|
-
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.
|
|
887
898
|
|
|
888
899
|
|
|
889
900
|
## Large histories and images
|
package/package.json
CHANGED
package/src/access-settings.mjs
CHANGED
|
@@ -10,7 +10,7 @@ import { validCapabilities } from "./model-capabilities.mjs";
|
|
|
10
10
|
|
|
11
11
|
export const CLIENT_IDS = Object.freeze(["codex", "claude_app", "claude_code"]);
|
|
12
12
|
export const CLIENT_NAMES = Object.freeze({ codex: "Codex App", claude_app: "Claude App", claude_code: "Claude Code" });
|
|
13
|
-
const APIS = ["messages", "responses", "chat"];
|
|
13
|
+
const APIS = ["messages", "responses", "chat", "gemini"];
|
|
14
14
|
const messages = {
|
|
15
15
|
ccdx_codex_catalog_cache_unavailable: "Codex model cache could not be refreshed safely. Close Codex App and try again; existing files were kept.",
|
|
16
16
|
ccdx_client_source_disabled: "CCDX access is paused. Enable the app and source, then select a model in the WebUI.",
|
|
@@ -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) => {
|
|
@@ -45,12 +46,14 @@ export function checkedApi(value) {
|
|
|
45
46
|
apiUrl(value.base_url);
|
|
46
47
|
const origin = new URL(value.base_url).origin;
|
|
47
48
|
for (const url of Object.values(value.endpoints)) if (new URL(apiUrl(url)).origin !== origin) throw accessError("ccdx_api_origin_mismatch");
|
|
49
|
+
if (value.endpoints.gemini && !new URL(value.endpoints.gemini).pathname.endsWith("/models")) throw accessError("ccdx_api_url_invalid");
|
|
48
50
|
const seen = new Set();
|
|
49
51
|
for (const model of value.models) {
|
|
50
52
|
if (model?.id === CODEX_AUTO_REVIEW_MODEL) throw accessError("ccdx_api_model_reserved");
|
|
51
53
|
if (!fields(model, ["id", "protocols", "context_window", "reasoning_efforts", "capabilities", "metadata"]) || !modelId(model.id) || seen.has(model.id)
|
|
52
54
|
|| !Array.isArray(model.protocols) || !model.protocols.length || new Set(model.protocols).size !== model.protocols.length
|
|
53
55
|
|| model.protocols.some(api => !value.endpoints[api])
|
|
56
|
+
|| model.protocols.includes("gemini") && !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,139}$/.test(model.id)
|
|
54
57
|
|| model.capabilities !== undefined && !validCapabilities(model.capabilities)
|
|
55
58
|
|| model.metadata !== undefined && (!fields(model.metadata, ["values", "protocols", "state", "checked_at", "deployment"]) || !validCapabilities(model.metadata.values)
|
|
56
59
|
|| model.metadata.protocols !== undefined && (!fields(model.metadata.protocols, APIS) || Object.values(model.metadata.protocols).some(value => !validCapabilities(value)))
|
package/src/adapter.mjs
CHANGED
|
@@ -27,6 +27,7 @@ import { createOptionalRoutes, isOptionalRoute, DASHBOARD_PATHS, DASHBOARD_API_P
|
|
|
27
27
|
import { createResponsesCompactHandler, createResponsesHandler } from "./responses-handler.mjs";
|
|
28
28
|
import { createResponsesImagePressureController } from "./responses-image-pressure.mjs";
|
|
29
29
|
import { createResponseFailureDiagnostics, createHttpFailureDiagnostics, buildHttpFailureDetails, isDiscoveryRequest } from "./response-failures.mjs";
|
|
30
|
+
import { createFailureHistory } from "./failure-history.mjs";
|
|
30
31
|
import { ADAPTER_CACHE_PATH } from "./cache-control.mjs";
|
|
31
32
|
import { loadRuntimeConfig, parsePositiveInteger } from "./runtime-config.mjs";
|
|
32
33
|
import {
|
|
@@ -173,13 +174,14 @@ export function createAdapterHandler(options = {}) {
|
|
|
173
174
|
|| codexClient.getCachedModelEndpoints;
|
|
174
175
|
const codexModelRegistry = options.codexModelRegistry || options.modelRegistry;
|
|
175
176
|
const openAIModelEnv = options.openAIModelEnv || process.env;
|
|
177
|
+
const runtimeConfig = options.env ? loadRuntimeConfig(options.env) : ADAPTER_RUNTIME_CONFIG;
|
|
176
178
|
const upstreamTimeoutMs = parsePositiveInteger(options.upstreamTimeoutMs, ADAPTER_RUNTIME_CONFIG.upstreamTimeoutMs);
|
|
177
179
|
const streamHandshakeTimeoutMs = parsePositiveInteger(options.streamHandshakeTimeoutMs, ADAPTER_RUNTIME_CONFIG.streamHandshakeTimeoutMs);
|
|
178
180
|
const streamIdleTimeoutMs = parsePositiveInteger(options.streamIdleTimeoutMs, ADAPTER_RUNTIME_CONFIG.streamIdleTimeoutMs);
|
|
179
181
|
const requestBodyTimeoutMs = parsePositiveInteger(options.requestBodyTimeoutMs, ADAPTER_RUNTIME_CONFIG.requestBodyTimeoutMs);
|
|
180
182
|
const acquireRequest = options.acquireRequest || createRequestAdmission({
|
|
181
183
|
maxBytes: inflightBodyLimitPreference({ env: options.env, home: options.dashboardOptions?.home }).bytes,
|
|
182
|
-
maxSupplementalBytes:
|
|
184
|
+
maxSupplementalBytes: runtimeConfig.maxInflightBodyBytes,
|
|
183
185
|
});
|
|
184
186
|
const requestMetrics = options.requestMetrics || createRequestMetrics();
|
|
185
187
|
const streamPerformanceMetrics = options.streamPerformanceMetrics || createStreamPerformanceMetrics({ routeNames: ["responses", "responses_compact", "antigravity"] });
|
|
@@ -198,18 +200,22 @@ export function createAdapterHandler(options = {}) {
|
|
|
198
200
|
antigravity = createAntigravityRuntime({ client: codexClient, models: () => codexModelRegistry?.models || [], privacy, compaction, acquireRequest,
|
|
199
201
|
applicationControl: options.dashboardOptions?.serviceControl?.applicationControl,
|
|
200
202
|
sourceAdmission: options.providerRuntime?.sourceAdmission,
|
|
203
|
+
nativeSources: () => options.providerRuntime?.antigravitySources?.() || [],
|
|
204
|
+
getSource: id => options.providerRuntime?.source?.(id),
|
|
201
205
|
applicationEvidence: options.providerRuntime?.applicationEvidence,
|
|
202
206
|
...(options.providerRuntime?.dashboardCatalog?{refreshModels:async()=>{
|
|
203
207
|
const result=await options.providerRuntime.dashboardCatalog({provider:"github"});
|
|
204
208
|
if(!result)throw httpError("GitHub model catalog refresh is unavailable",503);
|
|
205
209
|
}}:{}),
|
|
206
210
|
env: options.env, home: options.dashboardOptions?.home, requestBodyTimeoutMs, upstreamTimeoutMs, streamIdleTimeoutMs,
|
|
211
|
+
copilotTimeoutMs: runtimeConfig.antigravityCopilotTimeoutMs,
|
|
207
212
|
...options.antigravityOptions });
|
|
208
213
|
return antigravity;
|
|
209
214
|
})();
|
|
210
215
|
return antigravityLoading;
|
|
211
216
|
};
|
|
212
|
-
const
|
|
217
|
+
const failureHistory = createFailureHistory({ file: options.failureHistoryFile });
|
|
218
|
+
const httpErrors = createHttpFailureDiagnostics({ history: failureHistory });
|
|
213
219
|
const nativeImages = createNativeImagesHandler({ client: codexClient, acquireRequest, privacy, env: options.env, home: options.dashboardOptions?.home,
|
|
214
220
|
models: options.imageModels || (() => options.providerRuntime?.imageModels?.().models || imageModelCatalog(codexModelRegistry?.models)),
|
|
215
221
|
selection: options.imageSelection || (options.providerRuntime?.imageModels ? () => options.providerRuntime.imageModels().selected_model : undefined),
|
|
@@ -266,7 +272,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
266
272
|
let gemini;
|
|
267
273
|
try { const saved=readUserSettings({env:options.env,home:options.dashboardOptions?.home});gemini=antigravity?antigravity.snapshot():{configured:Object.hasOwn(saved,"gemini_antigravity_enabled"),enabled:saved.gemini_antigravity_enabled===true,route_observed:false}; }
|
|
268
274
|
catch { gemini={enabled:false,error:"ccdx_antigravity_settings_invalid"}; }
|
|
269
|
-
return { ...snapshot, gemini, http_errors: httpErrors.snapshot(), ...(providers ? { providers } : {}) };
|
|
275
|
+
return { ...snapshot, gemini, http_errors: { ...httpErrors.snapshot(), history: failureHistory.snapshot() }, ...(providers ? { providers } : {}) };
|
|
270
276
|
},
|
|
271
277
|
});
|
|
272
278
|
const responsesHandler = createResponsesHandler({
|
|
@@ -524,7 +530,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
524
530
|
if (trackRequest && (statusCode >= 400 || httpEvidence.model_error === true)) {
|
|
525
531
|
try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model || context?.requestedModel,
|
|
526
532
|
method: ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"].includes(req.method) ? req.method : "OTHER",
|
|
527
|
-
target: ["/v1/images/generations", "/v1/images/edits", "/v1/responses", "/v1/responses/compact", "/v1/alpha/search", "/anthropic/v1/messages", "/anthropic/v1/messages/count_tokens", "/anthropic/v1/models", "/mcp/image", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname) ? pathname : "unrecognized_path",
|
|
533
|
+
target: routeName === "antigravity" || ["/v1/images/generations", "/v1/images/edits", "/v1/responses", "/v1/responses/compact", "/v1/alpha/search", "/anthropic/v1/messages", "/anthropic/v1/messages/count_tokens", "/anthropic/v1/models", "/mcp/image", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname) ? pathname : "unrecognized_path",
|
|
528
534
|
request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.() ?? context?.upstreamAttempts ?? 0,
|
|
529
535
|
attempt_timings: streamPerformance?.attemptTimings?.(),
|
|
530
536
|
requested_model: context?.requestedModel, provider: context?.provider, application: context?.application || requestApplication(req.headers),
|
|
@@ -536,8 +542,11 @@ export function createAdapterHandler(options = {}) {
|
|
|
536
542
|
rejectionReason: httpEvidence.reason || (httpEvidence.code === "ccdx_client_source_disabled" ? httpEvidence.code : undefined) }); } catch {}
|
|
537
543
|
try { finishTerminalActivity(); } catch {}
|
|
538
544
|
try { context?.finishProvider?.(); } catch {}
|
|
539
|
-
if (applicationEvidenceScope && !aborted && statusCode >= 200 && statusCode < 300)
|
|
545
|
+
if (applicationEvidenceScope && !aborted && statusCode >= 200 && statusCode < 300) {
|
|
540
546
|
options.providerRuntime?.applicationEvidence?.accept(req, "codex", applicationEvidenceScope, applicationEvidenceAt);
|
|
547
|
+
if (context?.noteReviewModel && !httpEvidence.model_error)
|
|
548
|
+
try { context.noteReviewModel(); } catch { /* Optional model observation must not affect request completion. */ }
|
|
549
|
+
}
|
|
541
550
|
};
|
|
542
551
|
const containUnexpectedError = (error) => {
|
|
543
552
|
try { finishRequest({ statusCode: res.statusCode >= 400 ? res.statusCode : 500 }); } catch {}
|
|
@@ -167,7 +167,33 @@ export function chatFunctionPart(call, originalNames) {
|
|
|
167
167
|
return { functionCall: { id: call.id, name, args } };
|
|
168
168
|
}
|
|
169
169
|
|
|
170
|
-
|
|
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
|
|
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
|
-
|
|
193
|
-
if (event?.usage
|
|
194
|
-
|
|
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
|
|
273
|
+
...geminiUsage(usage) } };
|
|
244
274
|
}
|