codex-copilot-dx 1.3.22 → 1.3.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +3 -0
  2. package/docs/ARCHITECTURE.md +29 -1
  3. package/docs/REFERENCE.md +61 -1
  4. package/package.json +2 -2
  5. package/src/adapter.mjs +45 -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 +82 -0
  11. package/src/carbon-search.mjs +37 -0
  12. package/src/carbon-tool-bridge.mjs +384 -0
  13. package/src/cli-command-spec.mjs +2 -0
  14. package/src/cli-management.mjs +37 -8
  15. package/src/clients/codex-models.mjs +6 -2
  16. package/src/copilot-web-fetch.mjs +75 -0
  17. package/src/copilot-web.mjs +225 -0
  18. package/src/dashboard/connections.js +2 -1
  19. package/src/dashboard/console.js +1 -1
  20. package/src/dashboard/flow.js +2 -2
  21. package/src/dashboard/gemini.js +54 -0
  22. package/src/dashboard/index.html +30 -20
  23. package/src/dashboard/language.js +14 -0
  24. package/src/dashboard/status.js +4 -0
  25. package/src/dashboard/ui.js +3 -0
  26. package/src/dashboard-api.mjs +13 -0
  27. package/src/dashboard.mjs +17 -13
  28. package/src/gemini-app.mjs +34 -0
  29. package/src/http-transport.mjs +3 -2
  30. package/src/local-privacy.mjs +7 -1
  31. package/src/native-images.mjs +2 -1
  32. package/src/observability.mjs +5 -1
  33. package/src/optional-routes.mjs +4 -0
  34. package/src/privacy-stream.mjs +2 -0
  35. package/src/privacy-transform.mjs +1 -0
  36. package/src/providers/github.mjs +3 -1
  37. package/src/request-application.mjs +1 -1
  38. package/src/responses-bridge.mjs +14 -5
  39. package/src/responses-handler.mjs +24 -4
  40. package/src/stream-performance.mjs +1 -1
  41. 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 Antigravity page; inspect it with `ccdx app antigravity 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 Antigravity | `ccdx app antigravity 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)
@@ -643,7 +666,9 @@ Responses compatibility only rewrites a standalone tool output after an explicit
643
666
  missing-call-ID HTTP validation failure; the Chat bridge represents it as marked
644
667
  untrusted context. Valid paired outputs are unchanged. Tool-search, deferred and
645
668
  namespaced functions use native Responses when confirmed; Chat-only routes reject
646
- them instead of discarding those semantics. Allowed function lists retain their
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
647
672
  restriction and returned Chat calls are checked before completion. Chat cache
648
673
  fields are forwarded only when the catalog explicitly advertises each field.
649
674
 
@@ -893,6 +918,9 @@ the theme ring, with visibility/staleness and reduced-motion gates.
893
918
  stamps HTML resource URLs, and computes byte-specific ETags once. Sensitive and
894
919
  dynamic endpoints remain uncached. No shell/provider dependency is added to
895
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.
896
924
 
897
925
  `api-secrets.mjs` joins concurrent reads of one reference and prevents late
898
926
  reads from republishing after clear/set/remove. `providers/api.mjs` reuses the
package/docs/REFERENCE.md CHANGED
@@ -54,6 +54,47 @@ 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
+ ## Antigravity in Gemini App
58
+
59
+ The **Antigravity** page and `ccdx app antigravity 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` includes Antigravity before its first WebUI visit and uses observed state without waiting for native App
67
+ inspection. Use `app antigravity status` to check the signed installation explicitly.
68
+ The old `app gemini` commands remain available. Authorize Antigravity on the GitHub
69
+ Copilot source page, or with `source github access --edit --apps codex,antigravity --yes`.
70
+ Choose its exposed models on the Antigravity page or with
71
+ `app antigravity models --edit`. A model file uses `{"models":["<ccdx-copilot-model-id>"]}`.
72
+ Saving model selection requires reopening Gemini through CCDX to reload its model list.
73
+ The page distinguishes enabled access from an observed client connection.
74
+
75
+ Carbon and Argon appear with Low, Medium and High reasoning levels when the
76
+ Copilot account advertises them. Google models, account controls and defaults
77
+ are retained. Conversations keep their initial Google/Copilot source; start a
78
+ new conversation to change source. Unsupported PDF, audio and video inputs are refused
79
+ before Copilot dispatch. Text, inline images and native function tools are
80
+ converted to the advertised Copilot Chat interface; truncated streams report an
81
+ error rather than successful completion.
82
+
83
+ `enable` saves CCDX settings and prepares its local source guard. `open --preview` shows the launch plan.
84
+ `open` starts a closed, signed `/Applications/Gemini.app` with a process-local
85
+ Antigravity endpoint. An already running App is kept open and must be quit by
86
+ the user before reopening. Existing gateway environment settings cause a
87
+ conflict instead of being overwritten. The Gemini bundle, Google credentials,
88
+ global proxy and certificates are untouched. Endpoint adoption remains
89
+ unconfirmed until an Antigravity request is observed.
90
+
91
+ `disable` removes Copilot model access and refuses later Copilot/background
92
+ requests without sending them to Google. Quit and reopen Gemini through CCDX
93
+ after disabling to restore its native endpoint. This integration is separate
94
+ from the Codex/Claude source bindings and is off by default. Native-engine
95
+ replay alone does not establish parent-App adoption; observe actual original-App
96
+ requests and check ordinary Gemini chat when accepting a new App version.
97
+
57
98
  ## Context observations
58
99
 
59
100
  **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 +287,8 @@ history to fit a budget. Reasoning-budget conflicts and unsupported declared
246
287
  levels fail locally. Native search is recorded per protocol: Responses support
247
288
  does not imply Messages support. Native tool/citation/replay data remains on the
248
289
  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
290
+ added for custom APIs. GitHub Copilot's Gemini 4 Carbon uses its separate search
291
+ path described below. Exact input counting and compression thresholds are not proven by a small
250
292
  reply; the upstream still enforces its actual limits.
251
293
 
252
294
  Automatic sync can be disabled per client. Shared Claude fields are preserved
@@ -747,6 +789,24 @@ Changing the model or transport of a continuation can require removing incompati
747
789
 
748
790
  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.
749
791
 
792
+ GitHub Copilot's `gemini-4-carbon` uses Chat Completions. CCDX maps Codex custom,
793
+ namespaced and client-side tool-search calls to function tools and restores their
794
+ original identities in the reply and conversation history. The upstream receives
795
+ ordinary function tools; free-form grammar constraints are included in the tool
796
+ description rather than enforced by the Chat protocol. Other models retain their
797
+ existing routing and compatibility checks.
798
+
799
+ Carbon's standalone web search uses the current GitHub Copilot account. Only
800
+ search queries and requested constraints are sent to its search endpoint; the
801
+ conversation input and ChatGPT credentials are not forwarded. With live web
802
+ access, opening a page uses the installed macOS Copilot runtime and contacts the
803
+ page from the local machine. Cached mode returns indexed excerpts. Page reads
804
+ are limited to the first 20,000 characters, and image/literature search, PDF
805
+ screenshots, finance, weather and sports are not supported. Search references
806
+ are process-local and may expire; date restrictions are not guaranteed. A
807
+ configured domain policy that cannot be enforced is rejected. Local privacy
808
+ masking applies to the search commands when enabled.
809
+
750
810
  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.
751
811
 
752
812
  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.22",
4
- "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
3
+ "version": "1.3.24",
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": {
package/src/adapter.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { imageModelCatalog } from "./image-models.mjs";
2
2
  import http from "node:http";
3
+ import { readUserSettings } from "./user-settings.mjs";
3
4
  import { createNativeImagesHandler } from "./native-images.mjs";
4
5
  import { defaultCopilotClient } from "./copilot.mjs";
5
6
  import { buildCodexModelResponse } from "./codex-model-catalog.mjs";
@@ -175,16 +176,29 @@ export function createAdapterHandler(options = {}) {
175
176
  const requestBodyTimeoutMs = parsePositiveInteger(options.requestBodyTimeoutMs, ADAPTER_RUNTIME_CONFIG.requestBodyTimeoutMs);
176
177
  const acquireRequest = options.acquireRequest || createRequestAdmission();
177
178
  const requestMetrics = options.requestMetrics || createRequestMetrics();
178
- const streamPerformanceMetrics = options.streamPerformanceMetrics || createStreamPerformanceMetrics();
179
+ const streamPerformanceMetrics = options.streamPerformanceMetrics || createStreamPerformanceMetrics({ routeNames: ["responses", "responses_compact", "antigravity"] });
179
180
  const imagePressure = options.imagePressure || createResponsesImagePressureController();
180
181
  const responseFailures = options.responseFailures || createResponseFailureDiagnostics();
181
182
  const privacy = options.privacy || options.providerRuntime?.privacy || createLocalPrivacy({ env: options.env, home: options.dashboardOptions?.home });
183
+ let carbonSearch = null, copilotWeb = null;
184
+ let antigravity = null, antigravityLoading = null;
185
+ const geminiRuntime = async () => {
186
+ if (!antigravityLoading) antigravityLoading = (async () => {
187
+ const { createAntigravityRuntime } = await import("./antigravity-runtime.mjs");
188
+ antigravity = createAntigravityRuntime({ client: codexClient, models: () => codexModelRegistry?.models || [], privacy, acquireRequest,
189
+ env: options.env, home: options.dashboardOptions?.home, requestBodyTimeoutMs, upstreamTimeoutMs, streamIdleTimeoutMs,
190
+ ...options.antigravityOptions });
191
+ return antigravity;
192
+ })();
193
+ return antigravityLoading;
194
+ };
182
195
  const httpErrors = createHttpFailureDiagnostics();
183
196
  const nativeImages = createNativeImagesHandler({ client: codexClient, acquireRequest, privacy, env: options.env, home: options.dashboardOptions?.home,
184
197
  models: options.imageModels || (() => options.providerRuntime?.imageModels?.().models || imageModelCatalog(codexModelRegistry?.models)),
185
198
  selection: options.imageSelection || (options.providerRuntime?.imageModels ? () => options.providerRuntime.imageModels().selected_model : undefined),
186
199
  requestBodyTimeoutMs, timeoutMs: options.imageTimeoutMs, enabled: options.imagesEnabled, allowed: options.imagesAllowed });
187
200
  const optionalRoutes = createOptionalRoutes({ ...options, dashboardOptions: { ...options.dashboardOptions,
201
+ geminiFn: async (input, baseUrl) => (await geminiRuntime()).action(input, baseUrl),
188
202
  privacy,
189
203
  contextSnapshotFn: () => {
190
204
  const snapshots = [streamPerformanceMetrics.contextSnapshot?.(), options.providerRuntime?.claudePerformance?.contextSnapshot?.()];
@@ -200,7 +214,7 @@ export function createAdapterHandler(options = {}) {
200
214
  sources: [requestMetrics, streamPerformanceMetrics, options.providerRuntime?.claudePerformance, privacy],
201
215
  snapshot: () => {
202
216
  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);
217
+ const active = ["responses", "responses_compact", "messages", "search", "antigravity"].reduce((sum, route) => sum + (requests.by_route[route]?.active || 0), image?.active || 0);
204
218
  const claude = options.providerRuntime?.claudePerformance?.activitySnapshot?.();
205
219
  return { ...adapterHealthPayload(), scope: "activity", uptime_ms: Math.round(process.uptime() * 1000), local_privacy: privacy.snapshot(),
206
220
  model_activity: { active }, requests, runtime_usage: runtimeUsageSnapshot(),
@@ -232,7 +246,10 @@ export function createAdapterHandler(options = {}) {
232
246
  }
233
247
  try { snapshot.local_privacy = privacy.snapshot(); }
234
248
  catch { snapshot.local_privacy = { state: "error", error: "ccdx_privacy_settings_invalid" }; }
235
- return { ...snapshot, http_errors: httpErrors.snapshot(), ...(providers ? { providers } : {}) };
249
+ let gemini;
250
+ 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}; }
251
+ catch { gemini={enabled:false,error:"ccdx_antigravity_settings_invalid"}; }
252
+ return { ...snapshot, gemini, http_errors: httpErrors.snapshot(), ...(providers ? { providers } : {}) };
236
253
  },
237
254
  });
238
255
  const responsesHandler = createResponsesHandler({
@@ -302,6 +319,23 @@ export function createAdapterHandler(options = {}) {
302
319
  if (options.isDraining?.() && ![ADAPTER_STATUS_PATH, ADAPTER_HEALTH_PATH].includes(pathname)) {
303
320
  res.setHeader("Retry-After", "1");sendJsonError(res, httpError("CCDX is switching versions; retry shortly", 503));return;
304
321
  }
322
+ if (pathname === "/v1/alpha/search") {
323
+ if (req.method !== "POST") { res.setHeader?.("Allow", "POST");sendJsonError(res, httpError("Search requires POST", 405));return; }
324
+ if (!isLoopbackAddress(req.socket?.remoteAddress) || !req.headers?.host || !isLoopbackHostHeader(req.headers.host)
325
+ || Object.hasOwn(req.headers, "origin")) { sendJsonError(res, httpError("Search requires native local clients", 403));return; }
326
+ if (!carbonSearch) {
327
+ const { createCarbonSearchHandler } = await import("./carbon-search.mjs");
328
+ if (!options.carbonSearchFn) {
329
+ const { createCopilotWeb } = await import("./copilot-web.mjs");
330
+ copilotWeb = createCopilotWeb({ client: codexClient });
331
+ }
332
+ carbonSearch = createCarbonSearchHandler({ acquireRequest, privacy, requestBodyTimeoutMs, upstreamTimeoutMs,
333
+ searchFn: options.carbonSearchFn || copilotWeb.search,
334
+ resolveProvider: options.providerRuntime ? (body, request) =>
335
+ options.providerRuntime.resolveCodex?.(body, request) || options.providerRuntime.current(request) : undefined });
336
+ }
337
+ return carbonSearch(req, res);
338
+ }
305
339
  if (pathname.startsWith("/anthropic/")) {
306
340
  if (!isLoopbackAddress(req.socket?.remoteAddress) || !req.headers?.host || !isLoopbackHostHeader(req.headers.host)
307
341
  || Object.hasOwn(req.headers, "origin")) { sendJsonError(res, httpError("Claude requires native local clients", 403));return; }
@@ -412,6 +446,7 @@ export function createAdapterHandler(options = {}) {
412
446
  return sendRetiredClaudeSurface(res);
413
447
  }
414
448
 
449
+ if (pathname.startsWith("/antigravity/")) return (await geminiRuntime()).handle(req, res);
415
450
  res.writeHead(404, { "Content-Type": "application/json" });
416
451
  res.end(JSON.stringify({ error: "Not found" }));
417
452
  };
@@ -435,7 +470,8 @@ export function createAdapterHandler(options = {}) {
435
470
  return;
436
471
  }
437
472
 
438
- const trackRequest = pathname !== ADAPTER_HEALTH_PATH
473
+ const routeName = classifyAdapterRoute(req.method, pathname);
474
+ const trackRequest = routeName !== "antigravity_control" && pathname !== ADAPTER_HEALTH_PATH
439
475
  && pathname !== ACTIVITY_EVENTS_PATH
440
476
  && pathname !== ADAPTER_STATUS_PATH
441
477
  && pathname !== ADAPTER_CACHE_PATH
@@ -443,11 +479,10 @@ export function createAdapterHandler(options = {}) {
443
479
  && pathname !== PROVIDER_MANAGEMENT_PATH
444
480
  && !DASHBOARD_API_PATHS.has(pathname)
445
481
  && !((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname));
446
- const routeName = classifyAdapterRoute(req.method, pathname);
447
482
  const complete = trackRequest ? requestMetrics.begin(routeName) : () => {};
448
- const streamPerformance = trackRequest && !isDiscoveryRequest(req.method, pathname) ? streamPerformanceMetrics.begin(routeName, { requestId, application: requestApplication(req.headers) }) : null;
483
+ const streamPerformance = trackRequest && !isDiscoveryRequest(req.method, pathname) ? streamPerformanceMetrics.begin(routeName, { requestId, application: requestApplication(req.headers, routeName === "antigravity" ? "gemini_app" : "api") }) : null;
449
484
  let finishTerminalActivity = () => {};
450
- if (trackRequest && !isDiscoveryRequest(req.method, pathname) && ["responses", "responses_compact", "messages", "images", "image_mcp"].includes(routeName)) {
485
+ if (trackRequest && !isDiscoveryRequest(req.method, pathname) && ["responses", "responses_compact", "messages", "images", "image_mcp", "search", "antigravity"].includes(routeName)) {
451
486
  try {
452
487
  const finish = options.terminalActivity?.beginRequest?.();
453
488
  if (typeof finish === "function") finishTerminalActivity = finish;
@@ -461,7 +496,7 @@ export function createAdapterHandler(options = {}) {
461
496
  if (trackRequest && (statusCode >= 400 || httpEvidence.model_error === true)) {
462
497
  try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model || context?.requestedModel,
463
498
  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",
499
+ 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
500
  request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.() ?? context?.upstreamAttempts ?? 0,
466
501
  attempt_timings: streamPerformance?.attemptTimings?.(),
467
502
  requested_model: context?.requestedModel, provider: context?.provider, application: context?.application || requestApplication(req.headers),
@@ -530,13 +565,13 @@ export function createAdapterHandler(options = {}) {
530
565
  handler.snapshot = statusSnapshot;
531
566
  handler.subscribeActivity = activityEvents.subscribe;
532
567
  handler.closeActivity = activityEvents.close;
533
- handler.busy = () => optionalRoutes.busy() || options.providerRuntime?.busy?.() === true;
568
+ handler.busy = () => optionalRoutes.busy() || options.providerRuntime?.busy?.() === true || (antigravity?.snapshot().activity.active || 0) > 0;
534
569
  handler.exportState = () => ({ version: 1, history: exportResponseHistory(), optional: optionalRoutes.exportState() });
535
570
  handler.importState = async state => {
536
571
  if (state?.version !== 1) throw new Error("Unsupported service-state version");
537
572
  importResponseHistory(state.history);await optionalRoutes.importState(state.optional);
538
573
  };
539
- handler.cleanup = () => { activityEvents.close();optionalRoutes.dispose();if (!options.providerRuntime?.privacy) privacy.close(); };
574
+ handler.cleanup = () => { activityEvents.close();optionalRoutes.dispose();copilotWeb?.close();antigravity?.close();if (!options.providerRuntime?.privacy) privacy.close(); };
540
575
  return handler;
541
576
  }
542
577
 
@@ -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
+ }