codex-copilot-dx 1.3.21 → 1.3.23

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.
Files changed (49) hide show
  1. package/README.md +3 -0
  2. package/docs/ARCHITECTURE.md +48 -1
  3. package/docs/REFERENCE.md +60 -2
  4. package/package.json +3 -2
  5. package/src/adapter.mjs +41 -10
  6. package/src/antigravity-chat-bridge.mjs +240 -0
  7. package/src/antigravity-handler.mjs +141 -0
  8. package/src/antigravity-images.mjs +28 -0
  9. package/src/antigravity-models.mjs +34 -0
  10. package/src/antigravity-runtime.mjs +72 -0
  11. package/src/carbon-search.mjs +37 -0
  12. package/src/carbon-tool-bridge.mjs +384 -0
  13. package/src/claude-gateway.mjs +40 -3
  14. package/src/cli-command-spec.mjs +2 -0
  15. package/src/cli-management.mjs +14 -1
  16. package/src/clients/codex-models.mjs +6 -2
  17. package/src/copilot-responses-compat.mjs +9 -1
  18. package/src/copilot-web-fetch.mjs +75 -0
  19. package/src/copilot-web.mjs +225 -0
  20. package/src/dashboard/console.js +1 -1
  21. package/src/dashboard/flow.js +2 -2
  22. package/src/dashboard/gemini.js +27 -0
  23. package/src/dashboard/index.html +14 -20
  24. package/src/dashboard/language.js +10 -0
  25. package/src/dashboard/status.js +4 -0
  26. package/src/dashboard/ui.js +3 -0
  27. package/src/dashboard-api.mjs +13 -0
  28. package/src/dashboard.mjs +17 -13
  29. package/src/gemini-app.mjs +34 -0
  30. package/src/http-transport.mjs +3 -2
  31. package/src/local-privacy.mjs +7 -1
  32. package/src/messages-tool-schema.mjs +155 -0
  33. package/src/native-images.mjs +2 -1
  34. package/src/observability.mjs +5 -1
  35. package/src/optional-routes.mjs +4 -0
  36. package/src/privacy-stream.mjs +2 -0
  37. package/src/privacy-transform.mjs +1 -0
  38. package/src/providers/api-network.mjs +1 -1
  39. package/src/providers/api.mjs +27 -3
  40. package/src/providers/github.mjs +8 -5
  41. package/src/proxy-tunnel.mjs +17 -1
  42. package/src/request-application.mjs +1 -1
  43. package/src/responses-bridge.mjs +74 -9
  44. package/src/responses-chat-payload.mjs +6 -5
  45. package/src/responses-handler.mjs +29 -6
  46. package/src/responses-tool-output.mjs +42 -0
  47. package/src/safe-upstream-error.mjs +8 -2
  48. package/src/stream-performance.mjs +1 -1
  49. package/src/terminal-state.mjs +6 -5
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  Use your model services in **Codex App, Claude App and Claude Code** through one local gateway.
4
4
 
5
+ On macOS, the optional Gemini integration adds Copilot Carbon and Argon to the original App's Antigravity. Ordinary Gemini chat keeps Google. Set it up on the Gemini page; inspect it with `ccdx app gemini status`. Existing clients keep their setup.
6
+
5
7
  Connect GitHub Copilot, Microsoft 365 or your own API. Choose which apps can use each source, then select their models. CI and prebuilt releases cover **macOS on Apple Silicon** and **Windows on x64/ARM64**. Intel Mac code remains available, without CI coverage or new prebuilt assets.
6
8
 
7
9
  Optional local masking is off by default. Enable it in Settings → Local masking to download the model and component. Checks run locally and may add delay or mistake ordinary text; an unfinished check holds the request back. See [local masking](docs/REFERENCE.md#local-masking).
@@ -48,6 +50,7 @@ Model availability depends on your account and service. Microsoft 365 also requi
48
50
  | Sign in again | `ccdx source github reauth` |
49
51
  | Choose client models | `ccdx app codex models --edit` |
50
52
  | Preview client setup | `ccdx app claude-app sync --preview` |
53
+ | Set up Gemini Antigravity | `ccdx app gemini status` / `enable` / `open` |
51
54
  | Inspect failures | `ccdx requests --failed` |
52
55
  | Read usage | `ccdx usage` / `ccdx usage --scope run` |
53
56
  | Inspect preferences | `ccdx config show --effective` |
@@ -15,6 +15,29 @@ Client integration, image tools and the dashboard are not a general plugin frame
15
15
  | Management | CLI, dashboard, observability, package updates | Bounded metadata and explicit user actions |
16
16
  | Shared foundations | Codex paths, file locks, atomic files, network routes | No dependency on inference or dashboard rendering |
17
17
 
18
+ ## Gemini native boundary
19
+
20
+ `gemini-app.mjs` verifies the installed App and prepares a process-local
21
+ `CLOUD_CODE_URL` launch without editing its bundle or closing a running App.
22
+ `antigravity-runtime.mjs` owns explicit enablement, source-history protection and
23
+ the native management snapshot. The adapter loads it only for its management
24
+ or `/antigravity/` routes. Existing inference routes return before that dispatch.
25
+
26
+ `antigravity-handler.mjs` preserves observed Google account/catalog control
27
+ requests against fixed official Code Assist origins. It merges advertised
28
+ Copilot Carbon/Argon aliases while retaining native models and defaults. Native
29
+ Google agent requests pass through; selected Copilot agents and all unattributed
30
+ background inference use Copilot. Summaries use Carbon Low, searches use the
31
+ existing Copilot search transport, and images use the existing GHC Images API.
32
+ Ordinary Gemini chat is outside this endpoint scope; parent-App route adoption
33
+ and ordinary-chat isolation require native App acceptance beyond engine replay.
34
+
35
+ The Chat bridge keeps lossless tool integers, explicit effort, cancellation,
36
+ stream backpressure, privacy-token restoration and terminal errors. Native
37
+ conversation labels feed the existing source guard before main-answer dispatch.
38
+ Unsupported input fails explicitly, without Google or OpenAI inference fallback.
39
+ No independent WebKit client or private WebKit SPI is included.
40
+
18
41
  ## Composition and lifecycle
19
42
 
20
43
  ### Manual connection graph (1.2.13)
@@ -91,6 +114,10 @@ failed call; retirement waits for unrelated active responses to drain. Shutdown
91
114
  still closes all current/retiring transports. HTTP error statuses and intentional
92
115
  cancellation do not invalidate the transport. Node response streams are pulled
93
116
  on demand to avoid eager delivery into an already-cancelled Web stream.
117
+ For the API's Node HTTPS agent, idle sockets expire after at most 60 seconds,
118
+ or earlier when the server supplies a shorter keep-alive hint. The idle timeout
119
+ is removed on reuse, before an active request is attached. WinHTTP keeps its
120
+ existing OS-managed transport. Neither path retries an ambiguous sent request.
94
121
  `operation-error.mjs` projects fixed transport phases, a local error-code
95
122
  allowlist and socket-reuse evidence. API errors preserve their private cause,
96
123
  but client diagnostics/logs expose only those bounded fields, not raw causes,
@@ -635,6 +662,23 @@ Stream performance retains existing route totals and adds `by_route.<route>.by_p
635
662
 
636
663
  After Claude `message_stop`, the downstream response ends before an upstream drain. A complete drain permits connection reuse; cancellation, failure, one second or more than 64 KiB of tail bytes closes the reader. The last received chunk can exceed the byte threshold. Privacy masking preserves numeric literals in JSON-encoded tool arguments while restoring only mapped string values.
637
664
 
665
+ Responses compatibility only rewrites a standalone tool output after an explicit
666
+ missing-call-ID HTTP validation failure; the Chat bridge represents it as marked
667
+ untrusted context. Valid paired outputs are unchanged. Tool-search, deferred and
668
+ namespaced functions use native Responses when confirmed; Chat-only routes reject
669
+ them instead of discarding those semantics, except that GitHub Carbon maps its
670
+ client tools through a dedicated Chat bridge. Its Copilot search and page reader
671
+ load only when requested. Allowed function lists retain their
672
+ restriction and returned Chat calls are checked before completion. Chat cache
673
+ fields are forwarded only when the catalog explicitly advertises each field.
674
+
675
+ For an explicit root-combiner schema validation failure, the custom Messages
676
+ provider may send a bounded, model-facing object schema while retaining the
677
+ original validator for the response. Guarded tool frames are buffered until the
678
+ complete input passes that validator; invalid or numerically unsafe input is not
679
+ delivered as a tool call. Unsupported, complex or regular-expression schemas are
680
+ left unchanged. Ordinary accepted requests and streams bypass this adaptation.
681
+
638
682
  Byte-weighted request admission is not a simultaneous-stream limit. The 1.2.0 load replay exercises 16/64/128 small-body held streams, management responsiveness and downstream cancellation against 1.1.1. It does not establish a universal safe concurrency maximum. Existing defaults remain unchanged; see the release receipt for measured bounds.
639
683
 
640
684
  ## Installation and release delivery
@@ -874,6 +918,9 @@ the theme ring, with visibility/staleness and reduced-motion gates.
874
918
  stamps HTML resource URLs, and computes byte-specific ETags once. Sensitive and
875
919
  dynamic endpoints remain uncached. No shell/provider dependency is added to
876
920
  rendering, and no content-bearing response is reused across credential scopes.
921
+ Language and theme still load before rendering. The remaining scripts share one
922
+ deferred entrypoint in dependency order, so shared view globals and their
923
+ consumers arrive and execute together. Individual asset URLs remain available.
877
924
 
878
925
  `api-secrets.mjs` joins concurrent reads of one reference and prevents late
879
926
  reads from republishing after clear/set/remove. `providers/api.mjs` reuses the
@@ -1133,7 +1180,7 @@ The image and input-suggestion panels share `codex-launch-control.mjs`. `codex-a
1133
1180
 
1134
1181
  The managed Codex catalog projects explicit source input modalities ahead of native templates and checks GitHub priority eligibility against the full live source registry. Unknown modality metadata keeps the prior fallback. Source identities, selected models and routing remain unchanged.
1135
1182
 
1136
- `safe-upstream-error.mjs` reads only failed image or custom API responses, with a 64 KiB size bound, a 200 ms timer and four concurrent readers. Only fixed code/status pairs and local messages escape the reader. Original status, stable CCDX codes and validated Retry-After remain intact. Error-header callbacks release request admission before the optional body read; image processing slots are released at the same point. Count-token singleflight forwards those callbacks only to the appropriate waiters. Successful requests never invoke the reader.
1183
+ `safe-upstream-error.mjs` reads only failed image or custom API responses, with a 64 KiB size bound, a 200 ms timer and four concurrent readers. Only fixed code/status pairs and local messages escape the reader. Original status, stable CCDX codes and validated Retry-After remain intact. Error-header callbacks normally release request admission before the optional body read; an eligible explicit compatibility rejection retains admission through its one retry. Image processing slots are released before their error read. Count-token singleflight forwards callbacks only to the appropriate waiters. Successful requests never invoke the reader.
1137
1184
 
1138
1185
  ## Client updates and streaming boundaries (1.3.20)
1139
1186
 
package/docs/REFERENCE.md CHANGED
@@ -54,6 +54,41 @@ For scripts, source access accepts `--apps codex,claude-app` with `--edit`; edit
54
54
 
55
55
  An app model file contains `deployments: [{"source":"github","model":"<model-id>"}]`, with optional `default_model` and `auto_sync`. An explicit empty array clears the default and pauses access. A file without `deployments` is rejected. Unavailable saved selections remain visible until the user changes them.
56
56
 
57
+ ## Gemini App and Antigravity (candidate)
58
+
59
+ The optional **Gemini** page and `ccdx app gemini status|models|enable|disable|open`
60
+ manage the original macOS Gemini App. Enable requires acceptance of this data
61
+ scope: Antigravity main answers follow the selected Google or Copilot model;
62
+ all Antigravity summaries, searches and image generation use GitHub Copilot,
63
+ including background work from Google-model sessions. Ordinary Gemini chat
64
+ keeps its Google route. No OpenAI account or search fallback is used.
65
+
66
+ `app list` uses already observed Gemini state without waiting for native App
67
+ inspection. Use `app gemini status` to check the signed installation explicitly.
68
+
69
+ Carbon and Argon appear with Low, Medium and High reasoning levels when the
70
+ Copilot account advertises them. Google models, account controls and defaults
71
+ are retained. Conversations keep their initial Google/Copilot source; start a
72
+ new conversation to change source. Unsupported PDF, audio and video inputs are refused
73
+ before Copilot dispatch. Text, inline images and native function tools are
74
+ converted to the advertised Copilot Chat interface; truncated streams report an
75
+ error rather than successful completion.
76
+
77
+ `enable` saves CCDX settings and prepares its local source guard. `open --preview` shows the launch plan.
78
+ `open` starts a closed, signed `/Applications/Gemini.app` with a process-local
79
+ Antigravity endpoint. An already running App is kept open and must be quit by
80
+ the user before reopening. Existing gateway environment settings cause a
81
+ conflict instead of being overwritten. The Gemini bundle, Google credentials,
82
+ global proxy and certificates are untouched. Endpoint adoption remains
83
+ unconfirmed until an Antigravity request is observed.
84
+
85
+ `disable` removes Copilot model access and refuses later Copilot/background
86
+ requests without sending them to Google. Quit and reopen Gemini through CCDX
87
+ after disabling to restore its native endpoint. This integration is separate
88
+ from the Codex/Claude source bindings and is off by default. Native-engine
89
+ replay alone does not establish parent-App adoption; observe actual original-App
90
+ requests and check ordinary Gemini chat when accepting a new App version.
91
+
57
92
  ## Context observations
58
93
 
59
94
  **Usage → Context** shows reported input, declared model windows, cache reuse and observed gateway compactions from this process. It leaves missing values unknown. Input share is reported input divided by the declared window; it is not a measurement of every item currently held by the client. Reused input still occupies context.
@@ -246,7 +281,8 @@ history to fit a budget. Reasoning-budget conflicts and unsupported declared
246
281
  levels fail locally. Native search is recorded per protocol: Responses support
247
282
  does not imply Messages support. Native tool/citation/replay data remains on the
248
283
  existing protocol path; no shared search executor or external search account is
249
- added. Exact input counting and compression thresholds are not proven by a small
284
+ added for custom APIs. GitHub Copilot's Gemini 4 Carbon uses its separate search
285
+ path described below. Exact input counting and compression thresholds are not proven by a small
250
286
  reply; the upstream still enforces its actual limits.
251
287
 
252
288
  Automatic sync can be disabled per client. Shared Claude fields are preserved
@@ -588,7 +624,11 @@ was recreated on the original address, not that gray text appeared.
588
624
 
589
625
  ## Error delivery and conversation commits
590
626
 
591
- Image and custom API HTTP errors keep their stable `ccdx_images_http_<status>` or `ccdx_api_http_<status>` code, status and validated Retry-After. A failure-only reader can retain a small allowlist of structured source codes in `upstream_code`; source messages and bodies are not forwarded. Reads are limited to 64 KiB and a 200 ms timer, with at most four concurrent readers. Unknown or unfinished bodies fall back to the existing generic error. Request admission and image-generation slots are released before this optional read. Successful responses do not enter the reader. These changes do not introduce retries.
627
+ Image and custom API HTTP errors keep their stable `ccdx_images_http_<status>` or `ccdx_api_http_<status>` code, status and validated Retry-After. A failure-only reader can retain a small allowlist of structured source codes in `upstream_code`; source messages and bodies are not forwarded. Reads are limited to 64 KiB and a 200 ms timer, with at most four concurrent readers. Unknown or unfinished bodies fall back to the existing generic error. Admission is normally released before this read; a recognized compatibility rejection may hold it through one retry. Image-generation slots are still released before the read.
628
+
629
+ An explicit source validation error for a standalone tool output without a call ID can trigger one compatibility retry. An explicit rejection of a supported root-union tool schema can trigger one Messages retry; tool inputs are checked against the original schema before delivery. Schemas that cannot be checked safely remain unchanged. Other failures, including a silent connection, are not retried by these adaptations.
630
+
631
+ For custom APIs using the Node HTTPS agent, idle pooled connections are retired after 60 seconds at most, or earlier when the server declares a shorter keep-alive period. Active streams and their existing timeouts are unchanged. Windows WinHTTP continues to use its own connection handling. A connection can still fail within the idle period; reconnecting an expired connection can add setup time.
592
632
 
593
633
  Conversation-source admission and Messages checkpoint commits wait asynchronously for the existing cross-process locks. Cancellation ends lock waits. Checkpoint writes retain the primary/marker ordering and rollback behavior; the gateway awaits a successful commit before forwarding corresponding usable JSON or SSE output. Cached source checks keep their synchronous fast path. CLI configuration writers retain their existing synchronous behavior.
594
634
 
@@ -743,6 +783,24 @@ Changing the model or transport of a continuation can require removing incompati
743
783
 
744
784
  Native Responses forwards Codex `agent_message` items unchanged. When a model requires Chat Completions, CCDX frames them as messages from another agent, not human input or approval, retaining author/recipient, typed text/refusal/reasoning and representable image/screenshot content. Content unsupported by Chat, including file, audio or opaque encrypted parts, receives an explicit compatibility error instead of being serialized into ordinary text. This projection does not introduce another model request or change native Responses, Fast, Auto-review or compaction routing.
745
785
 
786
+ GitHub Copilot's `gemini-4-carbon` uses Chat Completions. CCDX maps Codex custom,
787
+ namespaced and client-side tool-search calls to function tools and restores their
788
+ original identities in the reply and conversation history. The upstream receives
789
+ ordinary function tools; free-form grammar constraints are included in the tool
790
+ description rather than enforced by the Chat protocol. Other models retain their
791
+ existing routing and compatibility checks.
792
+
793
+ Carbon's standalone web search uses the current GitHub Copilot account. Only
794
+ search queries and requested constraints are sent to its search endpoint; the
795
+ conversation input and ChatGPT credentials are not forwarded. With live web
796
+ access, opening a page uses the installed macOS Copilot runtime and contacts the
797
+ page from the local machine. Cached mode returns indexed excerpts. Page reads
798
+ are limited to the first 20,000 characters, and image/literature search, PDF
799
+ screenshots, finance, weather and sports are not supported. Search references
800
+ are process-local and may expire; date restrictions are not guaranteed. A
801
+ configured domain policy that cannot be enforced is rejected. Local privacy
802
+ masking applies to the search commands when enabled.
803
+
746
804
  After the stream handshake succeeds, stream liveness uses the idle timeout rather than the expired handshake deadline. Eligible HTTP-200 failure recovery acquires a bounded preparation budget and history admission before rebuilding its payload, then releases those reservations when the retry opens upstream or fails. Normal streams still release preparation admission after their response headers arrive.
747
805
 
748
806
  Messages and token counting stop the body-upload timer after JSON is read, then
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.3.21",
4
- "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
3
+ "version": "1.3.23",
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",
7
7
  "bin": {
@@ -54,6 +54,7 @@
54
54
  "test:release-network": "node scripts/release-network-replay.mjs"
55
55
  },
56
56
  "dependencies": {
57
+ "ajv": "8.18.0",
57
58
  "sharp": "0.35.5",
58
59
  "smol-toml": "1.9.1"
59
60
  },
package/src/adapter.mjs CHANGED
@@ -175,16 +175,29 @@ export function createAdapterHandler(options = {}) {
175
175
  const requestBodyTimeoutMs = parsePositiveInteger(options.requestBodyTimeoutMs, ADAPTER_RUNTIME_CONFIG.requestBodyTimeoutMs);
176
176
  const acquireRequest = options.acquireRequest || createRequestAdmission();
177
177
  const requestMetrics = options.requestMetrics || createRequestMetrics();
178
- const streamPerformanceMetrics = options.streamPerformanceMetrics || createStreamPerformanceMetrics();
178
+ const streamPerformanceMetrics = options.streamPerformanceMetrics || createStreamPerformanceMetrics({ routeNames: ["responses", "responses_compact", "antigravity"] });
179
179
  const imagePressure = options.imagePressure || createResponsesImagePressureController();
180
180
  const responseFailures = options.responseFailures || createResponseFailureDiagnostics();
181
181
  const privacy = options.privacy || options.providerRuntime?.privacy || createLocalPrivacy({ env: options.env, home: options.dashboardOptions?.home });
182
+ let carbonSearch = null, copilotWeb = null;
183
+ let antigravity = null, antigravityLoading = null;
184
+ const geminiRuntime = async () => {
185
+ if (!antigravityLoading) antigravityLoading = (async () => {
186
+ const { createAntigravityRuntime } = await import("./antigravity-runtime.mjs");
187
+ antigravity = createAntigravityRuntime({ client: codexClient, models: () => codexModelRegistry?.models || [], privacy, acquireRequest,
188
+ env: options.env, home: options.dashboardOptions?.home, requestBodyTimeoutMs, upstreamTimeoutMs, streamIdleTimeoutMs,
189
+ ...options.antigravityOptions });
190
+ return antigravity;
191
+ })();
192
+ return antigravityLoading;
193
+ };
182
194
  const httpErrors = createHttpFailureDiagnostics();
183
195
  const nativeImages = createNativeImagesHandler({ client: codexClient, acquireRequest, privacy, env: options.env, home: options.dashboardOptions?.home,
184
196
  models: options.imageModels || (() => options.providerRuntime?.imageModels?.().models || imageModelCatalog(codexModelRegistry?.models)),
185
197
  selection: options.imageSelection || (options.providerRuntime?.imageModels ? () => options.providerRuntime.imageModels().selected_model : undefined),
186
198
  requestBodyTimeoutMs, timeoutMs: options.imageTimeoutMs, enabled: options.imagesEnabled, allowed: options.imagesAllowed });
187
199
  const optionalRoutes = createOptionalRoutes({ ...options, dashboardOptions: { ...options.dashboardOptions,
200
+ geminiFn: async (input, baseUrl) => (await geminiRuntime()).action(input, baseUrl),
188
201
  privacy,
189
202
  contextSnapshotFn: () => {
190
203
  const snapshots = [streamPerformanceMetrics.contextSnapshot?.(), options.providerRuntime?.claudePerformance?.contextSnapshot?.()];
@@ -200,7 +213,7 @@ export function createAdapterHandler(options = {}) {
200
213
  sources: [requestMetrics, streamPerformanceMetrics, options.providerRuntime?.claudePerformance, privacy],
201
214
  snapshot: () => {
202
215
  const requests = requestMetrics.snapshot(), image = nativeImages.stats();
203
- const active = ["responses", "responses_compact", "messages"].reduce((sum, route) => sum + requests.by_route[route].active, image?.active || 0);
216
+ const active = ["responses", "responses_compact", "messages", "search", "antigravity"].reduce((sum, route) => sum + (requests.by_route[route]?.active || 0), image?.active || 0);
204
217
  const claude = options.providerRuntime?.claudePerformance?.activitySnapshot?.();
205
218
  return { ...adapterHealthPayload(), scope: "activity", uptime_ms: Math.round(process.uptime() * 1000), local_privacy: privacy.snapshot(),
206
219
  model_activity: { active }, requests, runtime_usage: runtimeUsageSnapshot(),
@@ -232,7 +245,7 @@ export function createAdapterHandler(options = {}) {
232
245
  }
233
246
  try { snapshot.local_privacy = privacy.snapshot(); }
234
247
  catch { snapshot.local_privacy = { state: "error", error: "ccdx_privacy_settings_invalid" }; }
235
- return { ...snapshot, http_errors: httpErrors.snapshot(), ...(providers ? { providers } : {}) };
248
+ return { ...snapshot, ...(antigravity ? { gemini: antigravity.snapshot() } : {}), http_errors: httpErrors.snapshot(), ...(providers ? { providers } : {}) };
236
249
  },
237
250
  });
238
251
  const responsesHandler = createResponsesHandler({
@@ -302,6 +315,23 @@ export function createAdapterHandler(options = {}) {
302
315
  if (options.isDraining?.() && ![ADAPTER_STATUS_PATH, ADAPTER_HEALTH_PATH].includes(pathname)) {
303
316
  res.setHeader("Retry-After", "1");sendJsonError(res, httpError("CCDX is switching versions; retry shortly", 503));return;
304
317
  }
318
+ if (pathname === "/v1/alpha/search") {
319
+ if (req.method !== "POST") { res.setHeader?.("Allow", "POST");sendJsonError(res, httpError("Search requires POST", 405));return; }
320
+ if (!isLoopbackAddress(req.socket?.remoteAddress) || !req.headers?.host || !isLoopbackHostHeader(req.headers.host)
321
+ || Object.hasOwn(req.headers, "origin")) { sendJsonError(res, httpError("Search requires native local clients", 403));return; }
322
+ if (!carbonSearch) {
323
+ const { createCarbonSearchHandler } = await import("./carbon-search.mjs");
324
+ if (!options.carbonSearchFn) {
325
+ const { createCopilotWeb } = await import("./copilot-web.mjs");
326
+ copilotWeb = createCopilotWeb({ client: codexClient });
327
+ }
328
+ carbonSearch = createCarbonSearchHandler({ acquireRequest, privacy, requestBodyTimeoutMs, upstreamTimeoutMs,
329
+ searchFn: options.carbonSearchFn || copilotWeb.search,
330
+ resolveProvider: options.providerRuntime ? (body, request) =>
331
+ options.providerRuntime.resolveCodex?.(body, request) || options.providerRuntime.current(request) : undefined });
332
+ }
333
+ return carbonSearch(req, res);
334
+ }
305
335
  if (pathname.startsWith("/anthropic/")) {
306
336
  if (!isLoopbackAddress(req.socket?.remoteAddress) || !req.headers?.host || !isLoopbackHostHeader(req.headers.host)
307
337
  || Object.hasOwn(req.headers, "origin")) { sendJsonError(res, httpError("Claude requires native local clients", 403));return; }
@@ -412,6 +442,7 @@ export function createAdapterHandler(options = {}) {
412
442
  return sendRetiredClaudeSurface(res);
413
443
  }
414
444
 
445
+ if (pathname.startsWith("/antigravity/")) return (await geminiRuntime()).handle(req, res);
415
446
  res.writeHead(404, { "Content-Type": "application/json" });
416
447
  res.end(JSON.stringify({ error: "Not found" }));
417
448
  };
@@ -435,7 +466,8 @@ export function createAdapterHandler(options = {}) {
435
466
  return;
436
467
  }
437
468
 
438
- const trackRequest = pathname !== ADAPTER_HEALTH_PATH
469
+ const routeName = classifyAdapterRoute(req.method, pathname);
470
+ const trackRequest = routeName !== "antigravity_control" && pathname !== ADAPTER_HEALTH_PATH
439
471
  && pathname !== ACTIVITY_EVENTS_PATH
440
472
  && pathname !== ADAPTER_STATUS_PATH
441
473
  && pathname !== ADAPTER_CACHE_PATH
@@ -443,11 +475,10 @@ export function createAdapterHandler(options = {}) {
443
475
  && pathname !== PROVIDER_MANAGEMENT_PATH
444
476
  && !DASHBOARD_API_PATHS.has(pathname)
445
477
  && !((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname));
446
- const routeName = classifyAdapterRoute(req.method, pathname);
447
478
  const complete = trackRequest ? requestMetrics.begin(routeName) : () => {};
448
- const streamPerformance = trackRequest && !isDiscoveryRequest(req.method, pathname) ? streamPerformanceMetrics.begin(routeName, { requestId, application: requestApplication(req.headers) }) : null;
479
+ const streamPerformance = trackRequest && !isDiscoveryRequest(req.method, pathname) ? streamPerformanceMetrics.begin(routeName, { requestId, application: requestApplication(req.headers, routeName === "antigravity" ? "gemini_app" : "api") }) : null;
449
480
  let finishTerminalActivity = () => {};
450
- if (trackRequest && !isDiscoveryRequest(req.method, pathname) && ["responses", "responses_compact", "messages", "images", "image_mcp"].includes(routeName)) {
481
+ if (trackRequest && !isDiscoveryRequest(req.method, pathname) && ["responses", "responses_compact", "messages", "images", "image_mcp", "search", "antigravity"].includes(routeName)) {
451
482
  try {
452
483
  const finish = options.terminalActivity?.beginRequest?.();
453
484
  if (typeof finish === "function") finishTerminalActivity = finish;
@@ -461,7 +492,7 @@ export function createAdapterHandler(options = {}) {
461
492
  if (trackRequest && (statusCode >= 400 || httpEvidence.model_error === true)) {
462
493
  try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model || context?.requestedModel,
463
494
  method: ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"].includes(req.method) ? req.method : "OTHER",
464
- target: ["/v1/images/generations", "/v1/images/edits", "/v1/responses", "/v1/responses/compact", "/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",
495
+ 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",
465
496
  request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.() ?? context?.upstreamAttempts ?? 0,
466
497
  attempt_timings: streamPerformance?.attemptTimings?.(),
467
498
  requested_model: context?.requestedModel, provider: context?.provider, application: context?.application || requestApplication(req.headers),
@@ -530,13 +561,13 @@ export function createAdapterHandler(options = {}) {
530
561
  handler.snapshot = statusSnapshot;
531
562
  handler.subscribeActivity = activityEvents.subscribe;
532
563
  handler.closeActivity = activityEvents.close;
533
- handler.busy = () => optionalRoutes.busy() || options.providerRuntime?.busy?.() === true;
564
+ handler.busy = () => optionalRoutes.busy() || options.providerRuntime?.busy?.() === true || (antigravity?.snapshot().activity.active || 0) > 0;
534
565
  handler.exportState = () => ({ version: 1, history: exportResponseHistory(), optional: optionalRoutes.exportState() });
535
566
  handler.importState = async state => {
536
567
  if (state?.version !== 1) throw new Error("Unsupported service-state version");
537
568
  importResponseHistory(state.history);await optionalRoutes.importState(state.optional);
538
569
  };
539
- handler.cleanup = () => { activityEvents.close();optionalRoutes.dispose();if (!options.providerRuntime?.privacy) privacy.close(); };
570
+ handler.cleanup = () => { activityEvents.close();optionalRoutes.dispose();copilotWeb?.close();antigravity?.close();if (!options.providerRuntime?.privacy) privacy.close(); };
540
571
  return handler;
541
572
  }
542
573
 
@@ -0,0 +1,240 @@
1
+ import { createHash } from "node:crypto";
2
+ import { webStreamLines } from "./stream.mjs";
3
+ import { MAX_UPSTREAM_CHAT_SUCCESS_BODY_BYTES } from "./http-transport.mjs";
4
+ import { ToolArgumentDeltaGuard, upstreamChatStreamError } from "./stream-contract.mjs";
5
+
6
+ const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
7
+ const names = /^[A-Za-z0-9_-]{1,64}$/;
8
+ const types = new Set(["OBJECT", "ARRAY", "STRING", "NUMBER", "INTEGER", "BOOLEAN", "NULL"]);
9
+ const schemaChildren = new Set(["items", "additionalProperties", "not", "if", "then", "else", "contains", "propertyNames"]);
10
+ const schemaMaps = new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
11
+ const schemaLists = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
12
+
13
+ function invalid(message, statusCode = 400) {
14
+ return Object.assign(new Error(message), { code: "ccdx_antigravity_protocol", statusCode });
15
+ }
16
+
17
+ // Preserve the spelling of numbers which JavaScript cannot round-trip.
18
+ export function parseAntigravityJSON(text) {
19
+ return JSON.parse(text, (_key, value, context) => typeof value === "number" && String(value) !== context.source
20
+ ? JSON.rawJSON(context.source) : value);
21
+ }
22
+
23
+ function schemaForChat(schema) {
24
+ if (!object(schema)) throw invalid("Invalid Gemini function schema");
25
+ const result = {};
26
+ for (const [key, value] of Object.entries(schema)) {
27
+ if (key === "type" && typeof value === "string" && types.has(value)) result[key] = value.toLowerCase();
28
+ else if (schemaChildren.has(key) && object(value)) result[key] = schemaForChat(value);
29
+ else if (schemaMaps.has(key) && object(value)) result[key] = Object.fromEntries(Object.entries(value).map(([name, child]) => [name, schemaForChat(child)]));
30
+ else if (schemaLists.has(key) && Array.isArray(value)) result[key] = value.map(schemaForChat);
31
+ else result[key] = value;
32
+ }
33
+ return result;
34
+ }
35
+
36
+ function modelToolName(name) {
37
+ if (typeof name !== "string" || !name) throw invalid("Gemini function name is missing");
38
+ return names.test(name) ? name : "ccdx_" + createHash("sha256").update(name).digest("hex").slice(0, 40);
39
+ }
40
+
41
+ function imagePart(part) {
42
+ const inline = part.inlineData || part.inline_data;
43
+ if (!object(inline) || typeof (inline.mimeType || inline.mime_type) !== "string" || typeof inline.data !== "string")
44
+ throw invalid("Invalid inline image");
45
+ const mime = inline.mimeType || inline.mime_type;
46
+ if (!/^image\/[a-z0-9.+-]+$/i.test(mime)) throw invalid("This attachment is not supported by the Copilot Chat route");
47
+ return { type: "image_url", image_url: { url: `data:${mime};base64,${inline.data}` } };
48
+ }
49
+
50
+ function contentValue(parts) {
51
+ if (!parts.length) return null;
52
+ return parts.length === 1 && parts[0].type === "text" ? parts[0].text : parts;
53
+ }
54
+
55
+ export function antigravityToChat(request, { model, effort, stream = true } = {}) {
56
+ if (!object(request) || !Array.isArray(request.contents) || typeof model !== "string" || !model)
57
+ throw invalid("Invalid Gemini generation request");
58
+ if (Object.keys(request).some(key => !["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "labels", "sessionId"].includes(key))
59
+ || request.tools !== undefined && !Array.isArray(request.tools)) throw invalid("Unsupported Gemini request field");
60
+ const originalNames = new Map(), tools = [];
61
+ for (const group of request.tools || []) {
62
+ if (!object(group) || !Array.isArray(group.functionDeclarations) || Object.keys(group).some(key => key !== "functionDeclarations"))
63
+ throw invalid("This Gemini tool cannot be represented by Chat Completions");
64
+ for (const definition of group.functionDeclarations) {
65
+ if (!object(definition)) throw invalid("Invalid Gemini function definition");
66
+ const alias = modelToolName(definition.name), previous = originalNames.get(alias);
67
+ if (previous && previous !== definition.name) throw invalid("Gemini function names collide");
68
+ if (previous) throw invalid("Duplicate Gemini function definition");
69
+ originalNames.set(alias, definition.name);
70
+ const parameters = definition.parametersJsonSchema || definition.parameters || { type: "object", properties: {} };
71
+ tools.push({ type: "function", function: { name: alias,
72
+ ...(typeof definition.description === "string" ? { description: definition.description } : {}), parameters: schemaForChat(parameters) } });
73
+ }
74
+ }
75
+ const config = request.toolConfig?.functionCallingConfig;
76
+ if (request.toolConfig && (!object(config) || Object.keys(request.toolConfig).some(key => key !== "functionCallingConfig")))
77
+ throw invalid("Unsupported Gemini tool configuration");
78
+ if (config?.allowedFunctionNames !== undefined) {
79
+ if (!Array.isArray(config.allowedFunctionNames) || config.allowedFunctionNames.some(name => typeof name !== "string"))
80
+ throw invalid("Invalid allowed function list");
81
+ const allowed = new Set(config.allowedFunctionNames.map(modelToolName));
82
+ if ([...allowed].some(name => !originalNames.has(name))) throw invalid("Allowed function is not declared");
83
+ for (let i = tools.length - 1; i >= 0; i--) if (!allowed.has(tools[i].function.name)) tools.splice(i, 1);
84
+ }
85
+ const mode = config?.mode || "AUTO", choices = { AUTO: "auto", ANY: "required", NONE: "none" };
86
+ if (!Object.hasOwn(choices, mode)) throw invalid("Unsupported Gemini function calling mode");
87
+ if (mode === "ANY" && !tools.length) throw invalid("Required Gemini functions are unavailable");
88
+ const messages = [], pending = new Map(), queues = new Map();
89
+ if (request.systemInstruction) {
90
+ const parts = request.systemInstruction.parts;
91
+ if (!Array.isArray(parts) || parts.some(part => !object(part) || typeof part.text !== "string" || Object.keys(part).some(key => key !== "text")))
92
+ throw invalid("Unsupported Gemini system instruction");
93
+ messages.push({ role: "system", content: parts.map(part => part.text).join("") });
94
+ }
95
+ for (let i = 0; i < request.contents.length; i++) {
96
+ const item = request.contents[i], role = item?.role === "model" ? "assistant" : item?.role === "user" ? "user" : null;
97
+ if (!role || !Array.isArray(item.parts)) throw invalid("Invalid Gemini message");
98
+ let content = [], calls = [], reasoning = "";
99
+ const flush = () => {
100
+ if (!content.length && !calls.length && !reasoning) return;
101
+ messages.push({ role, content: contentValue(content), ...(reasoning ? { reasoning_content: reasoning } : {}), ...(calls.length ? { tool_calls: calls } : {}) });
102
+ content = [];calls = [];reasoning = "";
103
+ };
104
+ for (let j = 0; j < item.parts.length; j++) {
105
+ const part = item.parts[j];if (!object(part) || part.thoughtSignature || part.thought_signature) throw invalid("Unsupported Gemini message part");
106
+ const count = [typeof part.text === "string", Boolean(part.inlineData || part.inline_data), Boolean(part.functionCall), Boolean(part.functionResponse)].filter(Boolean).length;
107
+ if (count !== 1 || Object.keys(part).some(key => !["text", "thought", "inlineData", "inline_data", "functionCall", "functionResponse"].includes(key)))
108
+ throw invalid("Unsupported Gemini message part");
109
+ if (typeof part.text === "string") {
110
+ if (part.thought) { if (role !== "assistant") throw invalid("Invalid Gemini thought");reasoning += part.text; }
111
+ else content.push({ type: "text", text: part.text });
112
+ } else if (part.inlineData || part.inline_data) content.push(imagePart(part));
113
+ else if (part.functionCall) {
114
+ if (role !== "assistant" || !object(part.functionCall) || !object(part.functionCall.args)) throw invalid("Invalid Gemini function call");
115
+ const call = part.functionCall, alias = modelToolName(call.name), id = call.id || "call_" + createHash("sha256").update(`${i}\0${j}\0${call.name}`).digest("hex").slice(0, 24);
116
+ if (typeof id !== "string" || !id || pending.has(id)) throw invalid("Invalid Gemini function call ID");
117
+ pending.set(id, call.name);const queue = queues.get(call.name) || [];queue.push(id);queues.set(call.name, queue);
118
+ calls.push({ id, type: "function", function: { name: alias, arguments: JSON.stringify(call.args) } });
119
+ } else if (part.functionResponse) {
120
+ flush();const response = part.functionResponse;
121
+ if (!object(response) || typeof response.name !== "string" || !object(response.response)) throw invalid("Invalid Gemini function response");
122
+ const queue = queues.get(response.name) || [], id = response.id || queue[0];
123
+ if (!id || pending.get(id) !== response.name) throw invalid("Gemini function response has no matching call");
124
+ pending.delete(id);const at = queue.indexOf(id);if (at >= 0) queue.splice(at, 1);
125
+ messages.push({ role: "tool", tool_call_id: id, content: JSON.stringify(response.response) });
126
+ } else throw invalid("Unsupported Gemini message part");
127
+ }
128
+ flush();
129
+ }
130
+ if (pending.size) throw invalid("Gemini function call has no matching response");
131
+ const generation = request.generationConfig || {};
132
+ if (!object(generation)) throw invalid("Invalid Gemini generation configuration");
133
+ const supported = new Set(["maxOutputTokens", "temperature", "topP", "stopSequences", "thinkingConfig", "candidateCount"]);
134
+ if (Object.keys(generation).some(key => !supported.has(key)) || generation.candidateCount !== undefined && generation.candidateCount !== 1)
135
+ throw invalid("Unsupported Gemini generation configuration");
136
+ if (generation.thinkingConfig && (!object(generation.thinkingConfig)
137
+ || Object.keys(generation.thinkingConfig).some(key => !["includeThoughts", "thinkingBudget", "thinkingLevel"].includes(key))
138
+ || generation.thinkingConfig.thinkingBudget !== undefined && (!Number.isSafeInteger(generation.thinkingConfig.thinkingBudget)
139
+ || generation.thinkingConfig.thinkingBudget < -1
140
+ || !effort && ![0, -1].includes(generation.thinkingConfig.thinkingBudget))))
141
+ throw invalid("Unsupported Gemini reasoning configuration");
142
+ // A CCDX model alias advertises the Copilot effort selected in the App.
143
+ // Its explicit effort takes precedence over Google's internal token budget.
144
+ const level = effort || generation.thinkingConfig?.thinkingLevel?.toLowerCase();
145
+ if (level && !["low", "medium", "high"].includes(level)) throw invalid("Unsupported Gemini reasoning level");
146
+ const chat = { model, messages, stream,
147
+ ...(stream ? { stream_options: { include_usage: true } } : {}),
148
+ ...(tools.length ? { tools, tool_choice: choices[mode] } : {}),
149
+ ...(generation.maxOutputTokens !== undefined ? { max_completion_tokens: generation.maxOutputTokens } : {}),
150
+ ...(generation.temperature !== undefined ? { temperature: generation.temperature } : {}),
151
+ ...(generation.topP !== undefined ? { top_p: generation.topP } : {}),
152
+ ...(generation.stopSequences !== undefined ? { stop: generation.stopSequences } : {}),
153
+ ...(level ? { reasoning_effort: level } : {}) };
154
+ const allowedNames = mode === "NONE" ? new Map() : new Map(tools.map(tool => [tool.function.name, originalNames.get(tool.function.name)]));
155
+ return { chat, originalNames: allowedNames };
156
+ }
157
+
158
+ export function chatFunctionPart(call, originalNames) {
159
+ const name = originalNames.get(call?.function?.name);
160
+ if (!name || typeof call?.id !== "string" || !call.id || typeof call.function.arguments !== "string")
161
+ throw invalid("Invalid upstream Chat function call", 502);
162
+ let args;try { args = parseAntigravityJSON(call.function.arguments); } catch { throw invalid("Invalid upstream Chat function arguments", 502); }
163
+ if (!object(args)) throw invalid("Invalid upstream Chat function arguments", 502);
164
+ return { functionCall: { id: call.id, name, args } };
165
+ }
166
+
167
+ export function chatToAntigravity(response, originalNames) {
168
+ const choice = response?.choices?.[0], message = choice?.message;
169
+ if (!object(message)) throw invalid("Invalid upstream Chat response", 502);
170
+ const parts = [];
171
+ if (typeof message.reasoning_content === "string" && message.reasoning_content) parts.push({ text: message.reasoning_content, thought: true });
172
+ if (typeof message.content === "string" && message.content) parts.push({ text: message.content });
173
+ if (Array.isArray(message.tool_calls)) for (const call of message.tool_calls) parts.push(chatFunctionPart(call, originalNames));
174
+ const finish = { stop: "STOP", tool_calls: "STOP", length: "MAX_TOKENS", content_filter: "SAFETY" }[choice.finish_reason];
175
+ if (!finish || finish === "STOP" && !parts.some(part => !part.thought)) throw invalid("Upstream Chat response did not complete", 502);
176
+ const usage = response.usage;
177
+ return { candidates: [{ content: { role: "model", parts }, finishReason: finish, index: 0 }],
178
+ ...(usage ? { usageMetadata: { promptTokenCount: usage.prompt_tokens || 0, candidatesTokenCount: usage.completion_tokens || 0, totalTokenCount: usage.total_tokens || 0 } } : {}) };
179
+ }
180
+
181
+ export async function* chatStreamToAntigravity(response, originalNames, { onChunk } = {}) {
182
+ if (!response?.body) throw invalid("Upstream Chat stream has no body", 502);
183
+ const calls = new Map(), data = [], guard = new ToolArgumentDeltaGuard();let done = false, finish = null, usage = null, bytes = 0, visible = false;
184
+ const frame = async function* () {
185
+ if (!data.length) return;
186
+ const raw = data.join("\n");data.length = 0;
187
+ if (raw === "[DONE]") { done = true;return; }
188
+ let event;try { event = JSON.parse(raw); } catch { throw invalid("Invalid upstream Chat stream event", 502); }
189
+ const upstreamError = upstreamChatStreamError(event);if (upstreamError) throw upstreamError;
190
+ if (event?.usage) usage = event.usage;
191
+ const choice = event?.choices?.[0];
192
+ if (!choice) return;
193
+ if (choice.finish_reason) finish = choice.finish_reason;
194
+ const delta = choice.delta || {};
195
+ for (const [key, thought] of [["reasoning_content", true], ["content", false], ["refusal", false]]) {
196
+ if (delta[key] === undefined || delta[key] === null || delta[key] === "") continue;
197
+ if (typeof delta[key] !== "string") throw invalid("Unsupported upstream Chat stream content", 502);
198
+ if (!thought) visible = true;
199
+ yield { response: { candidates: [{ index: 0, content: { role: "model", parts: [{ text: delta[key], ...(thought ? { thought: true } : {}) }] } }] } };
200
+ }
201
+ if (delta.function_call) throw invalid("Unsupported upstream Chat function call", 502);
202
+ if (delta.tool_calls !== undefined && !Array.isArray(delta.tool_calls)) throw invalid("Invalid upstream Chat tool calls", 502);
203
+ for (const call of delta.tool_calls || []) {
204
+ if (!Number.isSafeInteger(call.index) || call.index < 0 || call.index > 255) throw invalid("Invalid upstream Chat tool index", 502);
205
+ let state = calls.get(call.index);
206
+ if (!state) { state = { id: "", function: { name: "", arguments: "" } };calls.set(call.index, state); }
207
+ if (call.id) {
208
+ if (typeof call.id !== "string") throw invalid("Invalid upstream Chat tool ID", 502);
209
+ if (state.id && state.id !== call.id) throw invalid("Upstream Chat tool ID changed", 502);
210
+ state.id = call.id;
211
+ }
212
+ if (call.function?.name) {
213
+ if (typeof call.function.name !== "string") throw invalid("Invalid upstream Chat tool name", 502);
214
+ const name = call.function.name, duplicate = name === state.function.name && originalNames.has(name)
215
+ && ![...originalNames.keys()].some(declared => declared.startsWith(state.function.name + name));
216
+ if (!duplicate) state.function.name += name;
217
+ }
218
+ if (call.function?.arguments) {
219
+ if (typeof call.function.arguments !== "string") throw invalid("Invalid upstream Chat tool arguments", 502);
220
+ guard.observe(call.index, call.function.arguments);
221
+ state.function.arguments += call.function.arguments;bytes += Buffer.byteLength(call.function.arguments);
222
+ }
223
+ if (bytes > MAX_UPSTREAM_CHAT_SUCCESS_BODY_BYTES) throw invalid("Upstream Chat tool arguments are too large", 502);
224
+ }
225
+ };
226
+ for await (const line of webStreamLines(response, { onChunk })) {
227
+ if (!line) { yield* frame();if (done) break;continue; }
228
+ if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
229
+ }
230
+ if (!done && data.length) yield* frame();
231
+ if (!done || !finish) throw invalid("Upstream Chat stream ended before completion", 502);
232
+ const finishReason = { stop: "STOP", tool_calls: "STOP", length: "MAX_TOKENS", content_filter: "SAFETY" }[finish];
233
+ if (!finishReason || finish === "tool_calls" && !calls.size || finish !== "tool_calls" && calls.size || finish === "stop" && !visible)
234
+ throw invalid("Invalid upstream Chat stream completion", 502);
235
+ for (const [, call] of [...calls].sort(([a], [b]) => a - b)) {
236
+ yield { response: { candidates: [{ index: 0, content: { role: "model", parts: [chatFunctionPart(call, originalNames)] } }] } };
237
+ }
238
+ yield { response: { candidates: [{ index: 0, finishReason }],
239
+ ...(usage ? { usageMetadata: { promptTokenCount: usage.prompt_tokens || 0, candidatesTokenCount: usage.completion_tokens || 0, totalTokenCount: usage.total_tokens || 0 } } : {}) } };
240
+ }