codex-copilot-dx 1.4.7 → 1.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/REFERENCE.md CHANGED
@@ -85,7 +85,7 @@ Choose its exposed models on the Antigravity page or with
85
85
  `app antigravity models --edit`. Each WebUI row represents one model. Compatible Gemini chat models come from the current GitHub catalog, rather than a fixed Carbon/Argon list. The Reasoning column lists advertised levels, including Hydrogen's `xhigh` when available. The model checkbox controls visibility. Save/Discard, refresh, navigation, pausing and an off/on toggle preserve an existing saved route subset. CLI model editing and model files remain available for fine-grained effort selection. Refresh on this page or run `app antigravity models --refresh` to read the upstream catalog through the existing GitHub refresh runtime. Refresh does not change saved choices, save drafts, restart clients or invoke inference; failed reads retain the last usable list.
86
86
 
87
87
  The native Gemini catalog still uses distinct routing aliases for each level so its original selector can choose the intended effort. JSON model output retains those aliases for compatibility, with a `model` field identifying the actual model; the management status also includes `model_groups`. A model file accepts `{"models":["gemini-4-hydrogen"]}` to expose all of its advertised levels, or individual `ccdx-copilot-...-<effort>` aliases to choose a subset. Existing Carbon/Argon aliases remain valid. Models without declared reasoning levels use one plain alias.
88
- After saving, the Antigravity page reports whether the client has fetched the current model list. If the list is pending, reopen Gemini through CCDX.
88
+ In the **New chat default** column, choose **Set default** on a Copilot model row, or choose **Use app default** to clear the preference on save. The row action uses `medium` if selected, otherwise the first selected level. `app antigravity models --edit` can choose an exact level; a model file can add `"default_model"` with a selected base ID or route alias, or `null` to clear. The gateway changes only the agent-default field in a compatible catalog; it leaves requests, existing conversation bindings, ordinary Gemini chat and background tasks unchanged. An unavailable saved default does not silently pick another Copilot model. The page reports when the catalog still needs to be loaded. Use **Reopen** in the Antigravity page when it indicates settings need loading. CCDX never reopens the app automatically. An observed connection or fetched catalog does not prove the app adopted the new default.
89
89
 
90
90
  The WebUI uses one authorization form for GitHub Copilot, Microsoft 365 and custom APIs. Source switches apply immediately. App-authorization and model checkboxes are drafts until **Save**; **Discard changes** restores the saved selection. Drafts survive refresh and navigation. Source authorization does not choose app models.
91
91
 
@@ -93,8 +93,7 @@ Pausing Antigravity Copilot access retains its saved model selection. Native Goo
93
93
 
94
94
  The page distinguishes enabled access from an observed client connection.
95
95
 
96
- Compatible Gemini models and their declared reasoning levels appear when the Copilot account advertises them. Image-only models, incompatible interfaces and explicitly unavailable models are excluded. Google models, account controls and defaults
97
- are retained. Conversations keep their initial Google/Copilot source; start a
96
+ Compatible Gemini models and their declared reasoning levels appear when the Copilot account advertises them. Image-only models, incompatible interfaces and explicitly unavailable models are excluded. Google models and account controls are retained. The app default is retained unless an available preferred Copilot model can be published in a compatible agent catalog. Conversations keep their initial Google/Copilot source; start a
98
97
  new conversation to change source. Unsupported PDF, audio and video inputs are refused
99
98
  before Copilot dispatch. Text, inline images and native function tools are
100
99
  converted to the advertised Copilot Chat interface; truncated streams report an
@@ -258,9 +257,9 @@ For an identified conversation, hovering a point in the input-history chart show
258
257
 
259
258
  ## Shared source concurrency
260
259
 
261
- In **Settings → Advanced: request limits**, **Shared request-body limit** sets the shared gateway reservation to 32–128 MiB (default 32 MiB). It applies at the next CCDX start. `ccdx config limits` shows the saved and running values. `CCDX_MAX_INFLIGHT_BODY_BYTES` still overrides the saved value. This control does not change per-request size limits, the decompressed-body or response-history pools, Claude's separate Messages queue, or provider concurrency. Increasing this limit does not fix a provider timeout. Antigravity control GETs without a framed body do not enter the upload queue.
260
+ In **Settings → Advanced: request limits**, **Shared request-body limit** sets the shared gateway reservation to 32–128 MiB (default 32 MiB). It applies at the next CCDX start. `ccdx config limits` shows the saved and running values. `CCDX_MAX_INFLIGHT_BODY_BYTES` still overrides the saved value. This control does not change per-request size limits, the decompressed-body or response-history pools, Claude's separate Messages queue, or provider concurrency. Increasing this limit does not fix a provider timeout. Antigravity control GETs without a framed body do not enter the upload queue. Allowlisted read-only control POSTs with a known, uncompressed body of at most 8 KiB use four independent slots and an eight-request waiting limit. Other requests still use the shared body queue. `ccdx status --json` reports the short queue under `gemini.activity.short_control_queue`.
262
261
 
263
- `ccdx status` shows the longest admitted wait in the gateway's local request-body queue. `status --json` retains the longest sample and up to 16 recent waits, including cancellations and timeouts. Samples record a route, request ID, wait reason and byte counts in memory; no request body or credential is retained. The existing request details distinguish local waiting from waiting for the selected source. Local waiting ends before the body is read, and source waiting ends before sending upstream.
262
+ `ccdx status` shows the longest admitted wait in the gateway's local request-body queue. `status --json` retains the longest sample and up to 16 recent waits, including cancellations and timeouts. Samples record a route, request ID, wait reason and byte counts in memory; no request body or credential is retained. The existing request details distinguish local waiting from waiting for the selected source. Local waiting ends before the body is read, and source waiting ends before sending upstream. For Antigravity Copilot Chat, `ccdx status --json` reports how many body bytes were passed to the socket (`attempts[].body_written_bytes`), when the local send finished (`body_sent_ms`, measured from request receipt), the outbound client correlation ID (`client_request_id`), and any observed transport error (`transport_error`). The WebUI shows total duration, sending time, response-header wait and first usable output when available. Copy details keeps the local ID, outbound ID and upstream response ID distinct. Valid upstream retry guidance is preserved on 429 and 503; neither response triggers an automatic resend. A local timeout is not a recorded connection error. None of these markers prove the source received or processed the body.
264
263
 
265
264
  All three Apps share admission for the same configured source and account. A slot spans the real upstream response body through completion, cancellation or error. Request-body memory is tracked separately; uploads of unknown length start with a minimal reservation and grow it by bytes read, before retaining the data for parsing. If there is not enough room, reading pauses until existing requests release memory. Only one such reader per pool may grow at a time; a reader waiting for more memory takes priority over new admissions. Once upload is complete, another reader can start while the earlier request retains its actual body reservation. Requests larger than the pool still run exclusively at the pool ceiling, subject to the existing per-request limits. Growth waits share the existing upload deadline and can appear in the body-read time; the entry queue is recorded separately. Recovery and internal summaries acquire fresh slots after the rejected response releases its slot.
266
265
 
@@ -856,7 +855,7 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
856
855
  | `CCDX_DISABLE_USAGE` | unset | Set to `1` to disable usage logging |
857
856
  | `CCDX_SHUTDOWN_TIMEOUT_MS` | `5000` | Time to drain active HTTP connections before forcing shutdown |
858
857
 
859
- Antigravity starts the body deadline after queue admission. Its generation requests release body reservations after the final upstream response opens, while keeping response-restoration state until completion. Queue exhaustion or timeout returns `503`; a body timeout returns `408`; upstream and compaction timeouts return `504`. Client cancellation releases queued or active reservations. These limits and queue ordering remain unchanged.
858
+ Antigravity starts the body deadline after queue admission. Its generation requests release body reservations after the final upstream response opens, while keeping response-restoration state until completion. Queue exhaustion or timeout returns `503`; a body timeout returns `408`; upstream and compaction timeouts return `504`. Client cancellation releases queued or active reservations. An HTTP success with no Copilot stream body returns `502` before CCDX opens its response stream.
860
859
 
861
860
  ## Usage logging
862
861
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.4.7",
3
+ "version": "1.4.9",
4
4
  "description": "Local gateway for Codex, Claude and Gemini Antigravity with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
@@ -1,10 +1,11 @@
1
+ import {createRequestAdmission} from "./request-admission.mjs";
1
2
  import {randomUUID,createHash} from "node:crypto";
2
3
  import {buildResponsesUsageRecord,recordUsage} from "./usage-store.mjs";
3
- import {createRequestAbort,abortErrorStatusCode,readJsonBody,readBoundedResponseText,writeOrDrain,httpError,sendJsonError} from "./http-transport.mjs";
4
- import {safeUpstreamResponseHeaders} from "./upstream-headers.mjs";
4
+ import {createRequestAbort,abortErrorStatusCode,readJsonBody,readBoundedResponseText,writeOrDrain,httpError,sendJsonError,sendUpstreamError} from "./http-transport.mjs";
5
+ import {safeUpstreamResponseHeaders,upstreamRejectionHeaders} from "./upstream-headers.mjs";
5
6
  import {isLoopbackAddress,isLoopbackHostHeader} from "./security.mjs";
6
7
  import {antigravityToChat,chatToAntigravity,chatStreamToAntigravity,parseAntigravityJSON} from "./antigravity-chat-bridge.mjs";
7
- import {ANTIGRAVITY_MODEL_PREFIX,antigravityCopilotModels,mergeAntigravityModels} from "./antigravity-models.mjs";
8
+ import {ANTIGRAVITY_MODEL_PREFIX,antigravityCopilotModels,hasAntigravityAgentDefault,mergeAntigravityModels} from "./antigravity-models.mjs";
8
9
  import {createPrivacyTextFragments} from "./privacy-stream.mjs";
9
10
  import {createGoogleResponseObserver,googleUsageEvent} from "./antigravity-usage.mjs";
10
11
  import {currentRequestContext,observeRequestedModel} from "./request-context.mjs";
@@ -19,6 +20,10 @@ const PREFIX="/antigravity";
19
20
  const MAX_REPLY=64*1024*1024;
20
21
  const GOOGLE_ORIGIN="https://daily-cloudcode-pa.googleapis.com";
21
22
  const controlMethods=new Set(["loadCodeAssist","fetchUserInfo","fetchAdminControls","fetchAvailableModels","retrieveUserQuotaSummary","listExperiments","buildWithGooglePlugins","writeTrajectoryAcls","cascadeNuxes"]);
23
+ const smallReadControls=new Set(["loadCodeAssist","fetchUserInfo","fetchAdminControls","fetchAvailableModels","retrieveUserQuotaSummary","listExperiments"]);
24
+ const CONTROL_BODY_BYTES=8*1024;
25
+ // Reserve a full slot so many tiny bodies cannot fan out unbounded upstream calls.
26
+ const controlSlot={headers:{"content-length":String(CONTROL_BODY_BYTES)}};
22
27
  const passthrough=body=>({body,count:0,restoreText:value=>value,restoreValue:value=>value,restoreToolValue:value=>value,release(){}});
23
28
  const nativeHeaders=req=>Object.fromEntries(["authorization","user-agent","x-goog-api-client","x-goog-user-project","accept"].filter(key=>typeof req.headers[key]==="string").map(key=>[key,req.headers[key]]));
24
29
 
@@ -37,13 +42,14 @@ function groundedSearch(result,query){
37
42
  groundingMetadata:{webSearchQueries:[query],groundingChunks:sources.map(item=>({web:{uri:item.url,title:item.title||item.url}}))}}]};
38
43
  }
39
44
 
40
- export function createAntigravityHandler({client,models=()=>[],selectedModels=()=>null,enabled=()=>false,privacy,searchFn,imageFn,guardSource,acquireRequest=async()=>()=>{},sourceAdmission,applicationEvidence,
45
+ export function createAntigravityHandler({client,models=()=>[],selectedModels=()=>null,defaultModel=()=>null,enabled=()=>false,privacy,searchFn,imageFn,guardSource,acquireRequest=async()=>()=>{},sourceAdmission,applicationEvidence,
41
46
  compaction,compactionProfile=()=>"github",rememberConversationSource=()=>{},resolveCompactionSource=()=>null,recordUsageFn=recordUsage,fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,streamIdleTimeoutMs=60000}={}) {
42
47
  if(![GOOGLE_ORIGIN,"https://cloudcode-pa.googleapis.com"].includes(googleOrigin))throw new Error("Unrecognized Google control origin");
43
- let active=0,observed=false,catalogModels=null;const nativeWindows=new Map();
48
+ const acquireControl=createRequestAdmission({maxBytes:4*CONTROL_BODY_BYTES,maxQueued:8});
49
+ let active=0,observed=false,catalogModels=null,catalogDefaultSupported=null,catalogDefaultModel=null;const nativeWindows=new Map();
44
50
  const counts={total:0,google:0,copilot:0,search:0,images:0,failed:0};
45
51
  const handler=async(req,res)=>{
46
- const abort=createRequestAbort(req,res);let release=()=>{},session,body,request,converted,phase="validation",usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
52
+ const abort=createRequestAbort(req,res);let release=()=>{},releaseControl,session,body,request,converted,phase="validation",usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
47
53
  const releaseInput=()=>{
48
54
  body=null;request=null;if(converted)converted.chat=null;if(session)session.body=null;
49
55
  const done=release;release=()=>{};done();
@@ -76,12 +82,15 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
76
82
  const length=req.headers["content-length"];
77
83
  const bodylessControl=req.method==="GET"&&controlMethods.has(method)&&req.headers["transfer-encoding"]===undefined
78
84
  &&(length===undefined||typeof length==="string"&&/^0+$/.test(length));
85
+ const smallControl=req.method==="POST"&&smallReadControls.has(method)&&req.headers["transfer-encoding"]===undefined
86
+ &&(req.headers["content-encoding"]===undefined||req.headers["content-encoding"]==="identity")
87
+ &&typeof length==="string"&&/^\d+$/.test(length)&&Number(length)<=CONTROL_BODY_BYTES;
79
88
  phase="admission";
80
- // A framed request still needs the existing reservation. A known control
81
- // GET with no body does not occupy space in the upload queue.
82
- if(!bodylessControl)release=await measureRequestStageAsync("admission",()=>acquireRequest(req,{signal:abort.signal,streamingBody:req.method==="POST"}));
89
+ if(smallControl)releaseControl=await measureRequestStageAsync("admission",()=>acquireControl(controlSlot,{signal:abort.signal}));
90
+ else if(!bodylessControl)release=await measureRequestStageAsync("admission",()=>acquireRequest(req,{signal:abort.signal,streamingBody:req.method==="POST"}));
83
91
  phase="body";abort.setTimeout(requestBodyTimeoutMs,"request_body_timeout");
84
- body=req.method==="POST"?await measureRequestStageAsync("body",()=>readJsonBody(req,{admission:release,signal:abort.signal,parse:parseBody})):null;
92
+ body=req.method==="POST"?await measureRequestStageAsync("body",()=>readJsonBody(req,{signal:abort.signal,parse:parseBody,
93
+ ...(smallControl?{maxBodyBytes:CONTROL_BODY_BYTES,maxDecodedBodyBytes:CONTROL_BODY_BYTES}:{admission:release})})):null;
85
94
  phase="preparation";
86
95
  const context=currentRequestContext();if(context)context.application="gemini_app";
87
96
  const compacting=isCompactionRequest("gemini",body);
@@ -123,7 +132,9 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
123
132
  if(method==="fetchAvailableModels"&&upstream.ok){
124
133
  const value=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:8*1024*1024,signal:abort.signal,label:"Google model catalog"}));
125
134
  nativeWindows.clear();for(const[id,entry]of Object.entries(value.models||{}).slice(0,256))if(Number.isSafeInteger(entry?.maxTokens)&&entry.maxTokens>0){nativeWindows.set(id,entry.maxTokens);if(typeof entry.model==="string")nativeWindows.set(entry.model,entry.maxTokens)}
126
- const merged=mergeAntigravityModels(value,models(),selectedModels());
135
+ const merged=mergeAntigravityModels(value,models(),selectedModels(),defaultModel());
136
+ catalogDefaultSupported=hasAntigravityAgentDefault(value);
137
+ catalogDefaultModel=catalogDefaultSupported&&merged.defaultAgentModelId.startsWith(ANTIGRAVITY_MODEL_PREFIX)?merged.defaultAgentModelId:null;
127
138
  catalogModels=Object.keys(merged.models).filter(id=>id.startsWith(ANTIGRAVITY_MODEL_PREFIX));
128
139
  res.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"});res.end(JSON.stringify(merged));return;
129
140
  }
@@ -201,7 +212,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
201
212
  converted=antigravityToChat(request,{model:target.model,effort:target.effort,reasoningEfforts:target.effort?[target.effort]:[],stream});
202
213
  markResponseModel(target.model);markRequestObservation({usage_state:"pending"});
203
214
  session=privacy?.prepareSession?await privacy.prepareSession(converted.chat,{protocol:"chat",client:"gemini",signal:abort.signal}):passthrough(converted.chat);
204
- const callOptions={signal:abort.signal,sourceBodyManaged:true,retryOptions:{retries:0},onUpstreamStart:()=>abort.setTimeout(upstreamTimeoutMs,"upstream_timeout")};
215
+ const callOptions={signal:abort.signal,sourceBodyManaged:true,observeBodyWrite:true,retryOptions:{retries:0},onUpstreamStart:()=>abort.setTimeout(upstreamTimeoutMs,"upstream_timeout")};
205
216
  phase="upstream";
206
217
  const upstream=compacting&&compaction?await compaction.run({body:session.body,protocol:"chat",scope:JSON.stringify(["gemini","github",compactionProfile()]),source:"github",client:"gemini",
207
218
  inputLimit:target.maxTokens,outputAllowance:session.body.max_completion_tokens||session.body.max_tokens||0,native:client.chatCompletions,options:callOptions,
@@ -209,13 +220,23 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
209
220
  releaseInput();
210
221
  markUpstreamHeaders(upstream.status);
211
222
  applicationEvidence?.accept(req,"antigravity","inference");
212
- if(!upstream.ok){markResponseErrorOrigin("upstream_http");await cancelSourceResponse(upstream).catch(()=>{});throw httpError("Copilot generation was refused (HTTP "+upstream.status+")",upstream.status)}
223
+ if(!upstream.ok){
224
+ const status=upstream.status,headers=upstreamRejectionHeaders(status,upstream.headers);
225
+ markResponseErrorOrigin("upstream_http");await cancelSourceResponse(upstream).catch(()=>{});
226
+ abort.signal.throwIfAborted();counts.failed++;outcome="failed";markResponseTerminal(outcome,{origin:"upstream_http"});
227
+ sendUpstreamError(res,{status,headers},JSON.stringify({error:"Copilot generation was refused (HTTP "+status+")"}));return;
228
+ }
213
229
  if(!stream){
214
230
  const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));captureUsage(data);
215
231
  const result=chatToAntigravity(data,converted.originalNames);markToolActivity(result,"gemini");
216
232
  outcome=result.candidates[0].finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome);
217
233
  res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response:session.restoreValue(result)}));return;
218
234
  }
235
+ if (!upstream.body) {
236
+ sourceResponseFailed(upstream);
237
+ markResponseErrorOrigin("upstream_event");
238
+ throw httpError("Upstream Chat stream has no body",502);
239
+ }
219
240
  const text=session.count?createPrivacyTextFragments(session):{push:value=>value,finish:()=>""};
220
241
  res.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache"});
221
242
  const emit=chunk=>writeOrDrain(res,"data: "+JSON.stringify(chunk)+"\n\n",{signal:abort.signal});
@@ -244,7 +265,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
244
265
  if(res.headersSent&&!res.writableEnded&&!res.destroyed){res.end("data: "+JSON.stringify({error:{code:error.statusCode||502,message:error.message}})+"\n\n");}
245
266
  else sendJsonError(res,error,error.statusCode||502);
246
267
  }finally{
247
- releaseInput();session?.release();abort.cleanup();active--;
268
+ releaseInput();releaseControl?.();session?.release();abort.cleanup();active--;
248
269
  if(usageEvent){
249
270
  const u=usageEvent.usage,record=buildResponsesUsageRecord({surface:"antigravity",mode:usageMode,model:usageModel,
250
271
  response:{id:usageEvent.id,model:usageEvent.model||usageModel,usage:u?{input_tokens:u.prompt_tokens,output_tokens:u.completion_tokens,
@@ -259,6 +280,10 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
259
280
  }
260
281
  }
261
282
  };
262
- handler.snapshot=()=>({enabled:enabled(),observed,catalog_models:catalogModels,active,...counts});
283
+ handler.snapshot=()=>{
284
+ const queue=acquireControl.diagnostics();
285
+ return {enabled:enabled(),observed,catalog_models:catalogModels,catalog_default_supported:catalogDefaultSupported,catalog_default_model:catalogDefaultModel,active,...counts,
286
+ short_control_queue:{active:queue.activeRequests,waiting:queue.queued,queued_total:queue.queuedTotal,rejected:queue.rejected,timed_out:queue.timedOut,wait_ms_max:queue.waitMsMax}};
287
+ };
263
288
  return handler;
264
289
  }
@@ -22,7 +22,14 @@ export function antigravityCopilotModels(catalog) {
22
22
  });
23
23
  }
24
24
 
25
- export function mergeAntigravityModels(googleCatalog,copilotCatalog,selection=null) {
25
+ // Use the upstream's existing agent-default field only when it names a model
26
+ // in the same catalog. Do not invent a default contract for an unknown catalog.
27
+ export function hasAntigravityAgentDefault(catalog) {
28
+ const id=catalog?.defaultAgentModelId;
29
+ return typeof id==="string"&&!!catalog.models&&Object.hasOwn(catalog.models,id);
30
+ }
31
+
32
+ export function mergeAntigravityModels(googleCatalog,copilotCatalog,selection=null,defaultModel=null) {
26
33
  if(!googleCatalog?.models||typeof googleCatalog.models!=="object"||Array.isArray(googleCatalog.models))throw new Error("Unrecognized Google model catalog");
27
34
  const entries=antigravityCopilotModels(copilotCatalog).filter(model=>selection===null||selection.includes(model.id)),models={...googleCatalog.models};
28
35
  if(!entries.length)return googleCatalog;
@@ -39,5 +46,6 @@ export function mergeAntigravityModels(googleCatalog,copilotCatalog,selection=nu
39
46
  const sort=sorts.find(item=>item.displayName?.toLowerCase()==="recommended")||sorts[0];
40
47
  sort.groups??=[];sort.groups[0]??={modelIds:[]};
41
48
  sort.groups[0].modelIds=[...(sort.groups[0].modelIds||[]),...entries.map(entry=>entry.id)];
42
- return {...googleCatalog,models,agentModelSorts:sorts};
49
+ return {...googleCatalog,models,agentModelSorts:sorts,
50
+ ...(hasAntigravityAgentDefault(googleCatalog)&&entries.some(entry=>entry.id===defaultModel)?{defaultAgentModelId:defaultModel}:{})};
43
51
  }
@@ -19,7 +19,8 @@ import {withFileLockSync} from "./lock.mjs";
19
19
  import {httpError} from "./http-errors.mjs";
20
20
  import {antigravityCopilotModels} from "./antigravity-models.mjs";
21
21
 
22
- const execute=promisify(execFile),key="gemini_antigravity_enabled",modelKey="gemini_antigravity_models";
22
+ const execute=promisify(execFile),key="gemini_antigravity_enabled",modelKey="gemini_antigravity_models",defaultKey="gemini_antigravity_default_model";
23
+ const validAlias=id=>typeof id==="string"&&/^ccdx-copilot-[a-z0-9._-]{1,140}$/.test(id);
23
24
 
24
25
  export function createAntigravityRuntime({client,models=()=>[],refreshModels,privacy,home=os.homedir(),env=process.env,inspect=inspectGeminiApp,
25
26
  exec=execute,searchFn,imageFn,guardSource,googleFetch,acquireRequest,applicationControl,readToken=()=>readSavedGithubToken(home),...timeouts}={}) {
@@ -35,8 +36,9 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
35
36
  const settings=()=>{
36
37
  const saved=readUserSettings({...options,strict:true});
37
38
  if(saved[key]!==undefined&&typeof saved[key]!=="boolean")throw httpError("Invalid Gemini integration setting",409);
38
- if(saved[modelKey]!==undefined&&(!Array.isArray(saved[modelKey])||saved[modelKey].length>100||new Set(saved[modelKey]).size!==saved[modelKey].length||saved[modelKey].some(id=>typeof id!=="string"||!/^ccdx-copilot-[a-z0-9._-]{1,140}$/.test(id))))throw httpError("Invalid Antigravity model selection",409);
39
- return {configured:Object.hasOwn(saved,key),enabled:saved[key]===true,selected_models:saved[modelKey]??null};
39
+ if(saved[modelKey]!==undefined&&(!Array.isArray(saved[modelKey])||saved[modelKey].length>100||new Set(saved[modelKey]).size!==saved[modelKey].length||saved[modelKey].some(id=>!validAlias(id))))throw httpError("Invalid Antigravity model selection",409);
40
+ if(saved[defaultKey]!==undefined&&!validAlias(saved[defaultKey]))throw httpError("Invalid Antigravity default model",409);
41
+ return {configured:Object.hasOwn(saved,key),enabled:saved[key]===true,selected_models:saved[modelKey]??null,default_model:saved[defaultKey]??null};
40
42
  };
41
43
  const available=()=>settings().enabled&&readAccessSettings(options).providers.github?models():[];
42
44
  const sourceGuard=guardSource||((body,source,signal)=>{
@@ -45,7 +47,7 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
45
47
  const profile=source==="github"?"codex:"+githubTokenFingerprint(readToken()||""):"google:gemini-native";
46
48
  return guard("gemini",profile,{messages:[]},{session_id:id},readClientGatewayKeys({...options,create:false}).codex,undefined,signal);
47
49
  });
48
- const handler=createAntigravityHandler({client,models:available,selectedModels:()=>settings().selected_models,enabled:()=>settings().configured,privacy,searchFn:searchFn||web.search,
50
+ const handler=createAntigravityHandler({client,models:available,selectedModels:()=>settings().selected_models,defaultModel:()=>settings().default_model,enabled:()=>settings().configured,privacy,searchFn:searchFn||web.search,
49
51
  imageFn:imageFn||createAntigravityImages({client,models:available,privacy}),guardSource:sourceGuard,compactionProfile:()=>githubTokenFingerprint(readToken()||""),
50
52
  rememberConversationSource(body,source){const key=conversationKey(body);if(!key||typeof body.model!=="string"||!/^[\w][\w./:@+-]{0,159}$/.test(body.model))return;conversationSources.delete(key);conversationSources.set(key,{source,model:body.model});while(conversationSources.size>256)conversationSources.delete(conversationSources.keys().next().value)},
51
53
  async resolveCompactionSource(body){
@@ -61,26 +63,29 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
61
63
  },fetchGoogle:googleFetch,acquireRequest,...timeouts});
62
64
  function snapshot(){
63
65
  const config=settings(),sourceEnabled=readAccessSettings(options).providers.github,activity=handler.snapshot();
64
- const listed=antigravityCopilotModels(models()).map(({id,model,displayName,effort,maxTokens})=>({id,model,name:displayName,effort,context_window:maxTokens,selected:config.selected_models===null||config.selected_models.includes(id)}));
66
+ const listed=antigravityCopilotModels(models()).map(({id,model,displayName,effort,maxTokens})=>({id,model,name:displayName,effort,context_window:maxTokens,default:id===config.default_model,selected:config.selected_models===null||config.selected_models.includes(id)}));
65
67
  const groups=new Map();
66
68
  for(const variant of listed){
67
- if(!groups.has(variant.model))groups.set(variant.model,{id:variant.model,name:variant.name.split(" · Copilot")[0],source:"github",context_window:variant.context_window,efforts:[]});
68
- groups.get(variant.model).efforts.push({id:variant.id,effort:variant.effort,selected:variant.selected});
69
+ if(!groups.has(variant.model))groups.set(variant.model,{id:variant.model,name:variant.name.split(" · Copilot")[0],source:"github",context_window:variant.context_window,default:false,efforts:[]});
70
+ const group=groups.get(variant.model);group.default||=variant.default;group.efforts.push({id:variant.id,effort:variant.effort,selected:variant.selected});
69
71
  }
70
72
  const expected=listed.filter(model=>model.selected).map(model=>model.id).sort();
71
- const reload=config.enabled&&sourceEnabled?(activity.catalog_models===null?null:JSON.stringify([...activity.catalog_models].sort())!==JSON.stringify(expected)):false;
73
+ const desiredDefault=expected.includes(config.default_model)?config.default_model:null;
74
+ const reload=config.enabled&&sourceEnabled?(activity.catalog_models===null?null:JSON.stringify([...activity.catalog_models].sort())!==JSON.stringify(expected)
75
+ ||activity.catalog_default_supported===true&&activity.catalog_default_model!==desiredDefault):false;
76
+ const defaultUnavailable=config.default_model!==null&&(!desiredDefault||activity.catalog_default_supported===false);
72
77
  const current=applicationControl?.snapshot().antigravity;
73
78
  const visibleApp=current?{status:current.status,version:current.version||null,pids:current.pid?[current.pid]:[]}:app;
74
- return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,models_reload_required:reload,app:visibleApp,application:current||null,route_observed:handler.snapshot().observed,
79
+ return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,default_model_unavailable:defaultUnavailable,models_reload_required:reload,app:visibleApp,application:current||null,route_observed:activity.observed,
75
80
  model_source:"Google + GitHub Copilot",background_source:"GitHub Copilot",ordinary_chat_source:"Google (unchanged)",
76
81
  compaction_source:"Observed conversation source; existing background policy when unassigned",
77
82
  models:listed,model_groups:[...groups.values()],activity,last_operation:lastOperation};
78
83
  }
79
84
  async function action(input={},baseUrl){
80
- if(input&&Object.keys(input).some(name=>!["action","accept_background_copilot","models"].includes(name)))throw httpError("Invalid Gemini operation",400);
85
+ if(input&&Object.keys(input).some(name=>!["action","accept_background_copilot","models","default_model"].includes(name)))throw httpError("Invalid Gemini operation",400);
81
86
  const operation=input.action||"status";
82
87
  if(!["status","summary","refresh","models","enable","disable","open","preview"].includes(operation))throw httpError("Unknown Gemini operation",400);
83
- if(input.models!==undefined&&operation!=="models")throw httpError("Models require the models operation",400);
88
+ if((input.models!==undefined||input.default_model!==undefined)&&operation!=="models")throw httpError("Models require the models operation",400);
84
89
  if(operation==="refresh"){
85
90
  if(!refreshModels)throw httpError("Antigravity model refresh is unavailable in this service",503);
86
91
  await refreshModels();lastOperation={action:operation,status:"models_refreshed"};
@@ -89,7 +94,13 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
89
94
  const ids=input.models,known=new Set(antigravityCopilotModels(models()).map(model=>model.id));
90
95
  if(!Array.isArray(ids)||ids.length>100||new Set(ids).size!==ids.length||ids.some(id=>!known.has(id)))throw httpError("Choose available Antigravity models",400);
91
96
  const file=userSettingsPath(options);fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});
92
- withFileLockSync(file+".lock",()=>{const saved=readUserSettings({...options,strict:true});atomicWriteFileIfChangedSync(file,JSON.stringify({...saved,[modelKey]:ids},null,2)+"\n",{mode:0o600})});
97
+ if(input.default_model!==undefined&&input.default_model!==null&&(!validAlias(input.default_model)||!ids.includes(input.default_model)))throw httpError("Choose a selected Antigravity model as the default",400);
98
+ withFileLockSync(file+".lock",()=>{
99
+ const saved=readUserSettings({...options,strict:true});saved[modelKey]=ids;
100
+ if(input.default_model!==undefined&&input.default_model!==null)saved[defaultKey]=input.default_model;
101
+ if(input.default_model===null||saved[defaultKey]!==undefined&&!ids.includes(saved[defaultKey]))delete saved[defaultKey];
102
+ atomicWriteFileIfChangedSync(file,JSON.stringify(saved,null,2)+"\n",{mode:0o600});
103
+ });
93
104
  lastOperation={action:operation,status:"models_saved"};
94
105
  }
95
106
  if(operation==="summary")return snapshot();
@@ -32,7 +32,7 @@ export async function inspectApplicationConfiguration(id, { port = 2026, host =
32
32
  || (value.provider === "ccdx_gateway" && sameUrl(value.gateway?.base_url, `http://${host}:${port}/v1`)) ? "configured" : "preserved";
33
33
  } else {
34
34
  let settings;try { settings = await read(userSettingsPath(options)); } catch (error) { if (error.code !== "ENOENT") throw error;settings = {}; }
35
- value = { enabled: settings.gemini_antigravity_enabled === true, models: settings.gemini_antigravity_models || null, port, host };
35
+ value = { enabled: settings.gemini_antigravity_enabled === true, models: settings.gemini_antigravity_models || null, defaultModel: settings.gemini_antigravity_default_model ?? null, port, host };
36
36
  state = value.enabled ? "configured" : "native";
37
37
  }
38
38
  const reload = { ...value };delete reload.key;
@@ -291,7 +291,7 @@ export function parseManagedCommand(args) {
291
291
  const extras = {
292
292
  source:
293
293
  "Status reads local/cached evidence. check/--refresh may contact the source; no inference.\nsource import --file FILE previews supplied metadata; --from cc-switch|magpie reads known local configuration on demand.\n--select N --apply saves one source using private key input; no client access is granted.\nSource access grants do not select client models. Disable previews affected clients.\nGitHub login and company-account selection are source-specific.\nChoose visible models and defaults with app <app> models --edit.",
294
- app: "Configured is not App adoption or process liveness. Unknown stays unknown.\nmodels shows the selected plan; Antigravity lists compatible Copilot models and their selection.\napp antigravity models --refresh reads the GitHub catalog without inference or changing saved choices.\nsource <id> models shows the upstream catalog.\nsetup/remove changes integration setup; pause/resume retains credentials.\nsync --preview shows the model/configuration plan, not a byte-level file diff.\nopen focuses an already-running app; check is read-only and sends no inference.\nrestart asks before a graceful reopen. No client program is force-restarted.",
294
+ app: "Configured is not App adoption or process liveness. Unknown stays unknown.\nmodels shows the selected plan; Antigravity lists compatible Copilot models, selected levels and the saved default. Its --edit also sets or clears the default.\napp antigravity models --refresh reads the GitHub catalog without inference or changing saved choices.\nsource <id> models shows the upstream catalog.\nsetup/remove changes integration setup; pause/resume retains credentials.\nsync --preview shows the model/configuration plan, not a byte-level file diff.\nopen focuses an already-running app; check is read-only and sends no inference.\nrestart asks before a graceful reopen. No client program is force-restarted.",
295
295
  config:
296
296
  "Only service and terminal preferences are in scope. Browser appearance stays in WebUI.\nReset keeps accounts, keys, model plans and chats and stores a pre-reset backup.\nSaved and effective values can differ; restart requirements remain explicit.",
297
297
  requests:
@@ -237,9 +237,9 @@ export async function runManagementCommand(command, options = {}) {
237
237
  }
238
238
  if(action==="models"&&flags.edit){
239
239
  const state=await request({path:"gemini",...(flags.refresh?{body:{action:"refresh"},timeoutMs:20000}:{})});
240
- let ids;
240
+ let ids, preferred;
241
241
  if(flags.file){
242
- const listed=readFile().models;if(!Array.isArray(listed))throw new Error("Model files require a models array.");
242
+ const file=readFile(),listed=file.models;preferred=file.default_model;if(!Array.isArray(listed))throw new Error("Model files require a models array.");
243
243
  ids=listed.flatMap(id=>state.model_groups?.find(model=>model.id===id)?.efforts.map(item=>item.id)||[id]);
244
244
  }
245
245
  else if(Array.isArray(state.model_groups)){
@@ -252,13 +252,26 @@ export async function runManagementCommand(command, options = {}) {
252
252
  }
253
253
  }else ids=(await choose(state.models.map(model=>model.name),state.models.flatMap((model,index)=>model.selected!==false?[index]:[]))).map(index=>state.models[index].id);
254
254
  if(!Array.isArray(ids)||new Set(ids).size!==ids.length||ids.some(id=>!state.models.some(model=>model.id===id)))throw new Error("Choose listed Antigravity model IDs.");
255
- if(flags.preview)return print({models:ids,saved:false});
256
- await confirm("Save Antigravity model selection? Reopen Gemini afterward to reload it.");
257
- return print(await request({path:"gemini",body:{action:"models",models:ids}}));
255
+ const available=state.models.filter(model=>ids.includes(model.id));
256
+ if(!flags.file&&available.length&&Object.hasOwn(state,"default_model")){
257
+ available.forEach((model,index)=>output.write(`${index+1}. ${terminalCell(model.name)}${model.id===state.default_model?" (default)":""}\n`));
258
+ const answer=(await ask("Default model number (Enter keeps it; none uses the app default): ")).trim();
259
+ if(answer==="none")preferred=null;
260
+ else if(answer){if(!/^\d+$/.test(answer)||!available[Number(answer)-1])throw new Error("Choose a listed default model number.");preferred=available[Number(answer)-1].id;}
261
+ }
262
+ if(preferred!==undefined&&preferred!==null&&!ids.includes(preferred)){
263
+ const choices=available.filter(item=>item.model===preferred);
264
+ preferred=(choices.find(item=>item.effort==="medium")||choices[0])?.id;
265
+ if(!preferred)throw new Error("Choose a selected Antigravity model as the default.");
266
+ }
267
+ const body={models:ids,...(preferred!==undefined?{default_model:preferred}:{})};
268
+ if(flags.preview)return print({...body,saved:false});
269
+ await confirm("Save Antigravity model settings? Reopen Gemini afterward to reload them.");
270
+ return print(await request({path:"gemini",body:{action:"models",...body}}));
258
271
  }
259
272
  const state = await request({ path: "gemini", ...(action==="models"&&flags.refresh?{body:{action:"refresh"},timeoutMs:20000}:["status", "models"].includes(action) ? {} : { body: { action: flags.preview ? "preview" : action, ...(action === "enable" ? { accept_background_copilot: true } : {}) }, timeoutMs: 20000 }) });
260
- if(action==="models"&&flags.format!=="json"&&state.model_groups)return print(state.model_groups.map(model=>({model:model.name,id:model.id,source:"GitHub Copilot",context:model.context_window,
261
- efforts:model.efforts.map(item=>(item.effort||"default")+(item.selected?" ✓":"")).join(" / ")})),[["model","Model"],["id","ID"],["source","Source"],["context","Context"],["efforts","Reasoning (selected ✓)"]]);
273
+ if(action==="models"&&flags.format!=="json"&&state.model_groups)return print(state.model_groups.map(model=>({model:model.name,id:model.id,source:"GitHub Copilot",context:model.context_window,default:model.default===true,
274
+ efforts:model.efforts.map(item=>(item.effort||"default")+(item.selected?" ✓":"")).join(" / ")})),[["model","Model"],["id","ID"],["source","Source"],["context","Context"],["efforts","Reasoning (selected ✓)"],["default","Default"]]);
262
275
  return print(action === "models" ? state.models : state);
263
276
  }
264
277
  const graph = await connection(), snapshot = (await readStatus()).data, view = projectTerminalState(snapshot);
@@ -91,6 +91,7 @@ export function createCopilotClientRuntime({
91
91
  fetchImpl,
92
92
  retryOptions,
93
93
  bodyText,
94
+ observeBodyWrite,
94
95
  onUpstreamStart,
95
96
  ...sourceOptions
96
97
  } = {}) {
@@ -106,14 +107,15 @@ export function createCopilotClientRuntime({
106
107
  initiator: computeInitiator(messages),
107
108
  vision: computeVision(messages),
108
109
  });
109
- headers["Content-Length"] = String(Buffer.byteLength(serializedBody));
110
- return sourceTransport({ ...sourceOptions, signal, onUpstreamStart }, { send: fetchCopilotUpstream, model: upstreamReq.model, bodyText: serializedBody, stream: upstreamReq.stream === true, observe: true,
111
- args: [`${tokenSession.getApiBase()}/chat/completions`, {
110
+ const bodyBytes = Buffer.byteLength(serializedBody);
111
+ headers["Content-Length"] = String(bodyBytes);
112
+ return sourceTransport({ ...sourceOptions, signal, onUpstreamStart }, { send: fetchCopilotUpstream, model: upstreamReq.model, bodyText: serializedBody, bodyBytes, stream: upstreamReq.stream === true, observe: true,
113
+ evidence: { payload_bytes: bodyBytes }, args: [`${tokenSession.getApiBase()}/chat/completions`, {
112
114
  method: "POST",
113
115
  headers,
114
116
  body: serializedBody,
115
117
  signal,
116
- }, { fetchImpl, ...retryOptions }] });
118
+ }, { fetchImpl, ...retryOptions, observeBodyWrite }] });
117
119
  }
118
120
 
119
121
  async function fetchModels({ signal, fetchImpl, retryOptions }) {
@@ -0,0 +1,63 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { channel } from "node:diagnostics_channel";
3
+
4
+ const scope = new AsyncLocalStorage();
5
+ const requests = new WeakMap();
6
+ const create = channel("undici:request:create");
7
+ const chunks = channel("undici:request:bodyChunkSent");
8
+ const sent = channel("undici:request:bodySent");
9
+ const errors = channel("undici:request:error");
10
+ const transportCodes = new Set(["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT", "UND_ERR_SOCKET", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH"]);
11
+ let active = 0;
12
+
13
+ function onCreate({ request }) {
14
+ const state = scope.getStore();
15
+ if (!state?.callback || state.request) return;
16
+ state.request = request;
17
+ requests.set(request, state);
18
+ state.callback("start");
19
+ }
20
+
21
+ function onChunk({ request, chunk }) {
22
+ const state = requests.get(request);
23
+ if (!state) return;
24
+ const bytes = typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk?.byteLength;
25
+ if (Number.isSafeInteger(bytes) && bytes > 0) state.callback("chunk", bytes);
26
+ }
27
+
28
+ function onSent({ request }) {
29
+ requests.get(request)?.callback("sent");
30
+ }
31
+
32
+ function onError({ request, error }) {
33
+ const state = requests.get(request);
34
+ // An intentional abort destroys the socket. Its error is not evidence that
35
+ // the connection had already failed.
36
+ if (!state || state.signal?.aborted || error?.name === "AbortError") return;
37
+ const code = error?.cause?.code || error?.code;
38
+ if (transportCodes.has(code)) state.callback("error", code);
39
+ }
40
+
41
+ // Only subscribe while an observed POST is open. Retain the request identity
42
+ // for correlation; do not read its URL, headers or body.
43
+ export async function fetchWithBodyWriteTiming(url, init, callback, fetchImpl = fetch) {
44
+ if (active++ === 0) {
45
+ create.subscribe(onCreate);
46
+ chunks.subscribe(onChunk);
47
+ sent.subscribe(onSent);
48
+ errors.subscribe(onError);
49
+ }
50
+ const state = { callback, request: null, signal: init.signal };
51
+ try {
52
+ return await scope.run(state, fetchImpl, url, init);
53
+ } finally {
54
+ if (state.request) requests.delete(state.request);
55
+ state.request = state.callback = null;
56
+ if (--active === 0) {
57
+ create.unsubscribe(onCreate);
58
+ chunks.unsubscribe(onChunk);
59
+ sent.unsubscribe(onSent);
60
+ errors.unsubscribe(onError);
61
+ }
62
+ }
63
+ }
package/src/copilot.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import { fetchWithBodyWriteTiming } from "./copilot-send-timing.mjs";
2
+ import { observeUpstreamBodyWrite } from "./stream-performance.mjs";
1
3
  import { randomUUID } from "node:crypto";
2
4
  import { status } from "./status.mjs";
3
5
  import { debugLog } from "./log.mjs";
@@ -160,6 +162,7 @@ export async function fetchCopilotUpstream(
160
162
  fetchImpl = fetch,
161
163
  retries = UPSTREAM_RETRIES,
162
164
  retryDelayMs = UPSTREAM_RETRY_DELAY_MS,
165
+ observeBodyWrite = false,
163
166
  } = {},
164
167
  ) {
165
168
  const retryCount = parseUpstreamRetries(retries);
@@ -173,7 +176,8 @@ export async function fetchCopilotUpstream(
173
176
  const attemptStart = Date.now();
174
177
  debugLog(`upstream ${method} ${target} attempt=${attempt + 1}/${retryCount + 1}`);
175
178
  try {
176
- const resp = await fetchImpl(url, init);
179
+ const onBodySent = observeBodyWrite && method === "POST" && fetchImpl === fetch && observeUpstreamBodyWrite(init.headers?.["X-Request-Id"]);
180
+ const resp = await (onBodySent ? fetchWithBodyWriteTiming(url, init, onBodySent) : fetchImpl(url, init));
177
181
  debugLog(`upstream ${method} ${target} status=${resp.status} attempt=${attempt + 1}/${retryCount + 1} attempt_ms=${Date.now() - attemptStart} total_ms=${Date.now() - totalStart}`);
178
182
  if (attempt < retryCount && isRetryableUpstreamStatus(resp.status, method)) {
179
183
  await discardBoundedResponseBody(resp);
@@ -1,9 +1,10 @@
1
1
  (() => {
2
2
  function create({ element: el, change, localize, isBusy = () => false }) {
3
- let data, pending = false, sequence = 0, confirmation = null, claudeApp = true, note = null, autoError = false;
3
+ let data, pending = false, sequence = 0, confirmation = null, claudeApp = true, note = null, autoError = false, antigravityCatalogPending = false;
4
4
  const route = () => ({ codex: "codex", claude: claudeApp ? "claude_app" : null, gemini: "antigravity" })[location.hash.slice(1)] || null;
5
5
  const label = (id, key) => localize(el(id), key);
6
- const buttonKey = state => state?.status === "running" ? state.needs_reload ? "application_reopen" : "application_focus"
6
+ const needsReload = state => state?.needs_reload || route() === "antigravity" && antigravityCatalogPending;
7
+ const buttonKey = state => state?.status === "running" ? needsReload(state) ? "application_reopen" : "application_focus"
7
8
  : state?.status === "starting" ? "application_opening" : state?.status === "stopped" ? "application_open" : "application_check";
8
9
  function render() {
9
10
  const id = route(), state = data?.applications?.[id];
@@ -15,7 +16,7 @@
15
16
  label("application-open-label", buttonKey(state));
16
17
  el("application-open").disabled = pending || isBusy() || ["starting", "unsupported", "not_installed", "multiple"].includes(state?.status);
17
18
  el("application-open").setAttribute("aria-busy", String(pending || isBusy() || state?.status === "starting"));
18
- label("application-state", note || (state?.status === "running" ? state.needs_reload ? "application_reload_pending" : state.connection === "observed" ? "application_connected" : "application_pending"
19
+ label("application-state", note || (state?.status === "running" ? needsReload(state) ? id === "antigravity" ? "gemini_settings_saved" : "application_reload_pending" : state.connection === "observed" ? "application_connected" : "application_pending"
19
20
  : state?.status === "stopped" ? "application_stopped" : state?.status === "starting" ? "application_opening" : "application_" + (state?.status || "unknown")));
20
21
  if (!pending) {
21
22
  el("codex-auto-launch").checked = data?.effective?.codex_auto_launch?.value === true;
@@ -47,7 +48,9 @@
47
48
  ...(operation === "restart" ? { confirmed: true, expected_pid: expected.pid, expected_started: expected.started } : {}) }, el("application-open"), { quiet: true });
48
49
  if (!next) { note = "application_action_failed";return; }
49
50
  data = next;const result = next.last_operation?.feature === "application" ? next.last_operation.result : null;
50
- if (["opened", "opening"].includes(result?.status)) for (const delay of [1000, 10500]) setTimeout(() => { if (route() === id && document.visibilityState === "visible") void check(true); }, delay);
51
+ if (["opened", "opening"].includes(result?.status)) for (const delay of [1000, 10500]) setTimeout(() => { if (route() === id && document.visibilityState === "visible") {
52
+ void check(true);if (id === "antigravity") void globalThis.ccdxAntigravity?.refreshStatus();
53
+ } }, delay);
51
54
  if (result && !["opened", "opening", "focused", "checked"].includes(result.status)) {
52
55
  const direct = { unknown: "application_unknown", app_check_failed: "application_unknown", not_installed: "application_not_installed", multiple: "application_multiple", multiple_apps: "application_multiple", unsupported: "application_unsupported", app_not_running: "application_stopped", app_route_conflict: "application_action_route_conflict" };
53
56
  note = direct[result.status] || (["open_failed", "focus_unavailable", "quit_refused", "quit_timeout", "app_changed", "needs_app_relaunch", "route_conflict"].includes(result.status) ? "application_action_" + result.status : "application_action_failed");
@@ -56,7 +59,7 @@
56
59
  }
57
60
  function openCurrent() {
58
61
  const id = route(), state = data?.applications?.[id];
59
- if (state?.status === "running" && state.needs_reload) { confirmation = { id, pid: state.pid, started: state.started };render(); }
62
+ if (state?.status === "running" && needsReload(state)) { confirmation = { id, pid: state.pid, started: state.started };render(); }
60
63
  else if (state?.status === "running") void act("focus");
61
64
  else if (state?.status === "stopped") void act("open");
62
65
  else void check(true);
@@ -75,6 +78,7 @@
75
78
  });
76
79
  window.addEventListener("focus", () => { if (document.visibilityState === "visible") void check(); });
77
80
  window.addEventListener("ccdx-gemini-state", event => {
81
+ antigravityCatalogPending = event.detail?.needsCatalogReload === true;
78
82
  const state = event.detail?.application;if (state) sync({ ...data, applications: { ...data?.applications, antigravity: state } });
79
83
  });
80
84
  return { sync, render, open(id) { if (route() === id && !pending && !isBusy()) openCurrent(); }, routeChanged() { confirmation = null;note = null;sequence++;render();void check(); }, refresh: () => check(true) };
@@ -1,12 +1,14 @@
1
1
  (() => {
2
2
  const el=id=>document.getElementById(id),language=globalThis.ccdxLanguage;
3
- let busy=false,state=null,draft=null,notice=null,pendingAction=null;
4
- let sharedApplication=null,sharedPending=false;
3
+ let busy=false,state=null,draft=null,defaultDraft,notice=null,pendingAction=null;
4
+ let sharedApplication=null,sharedPending=false,savedTimer,showSaved=false;
5
5
  const words=(id,key)=>language.set(el(id),key);
6
6
  const clear=id=>{el(id).removeAttribute('data-i18n');el(id).removeAttribute('data-i18n-args');el(id).textContent='';el(id).title=''};
7
- const controls=['gemini-enabled','gemini-open','gemini-refresh','gemini-save','gemini-cancel'];
7
+ const controls=['gemini-enabled','gemini-open','gemini-refresh','gemini-save','gemini-cancel','gemini-use-app-default'];
8
8
  const selected=()=>state?.models.filter(model=>model.selected!==false).map(model=>model.id)||[];
9
- const dirty=()=>draft!==null&&JSON.stringify([...draft].sort())!==JSON.stringify(selected().sort());
9
+ const savedDefault=()=>state?.default_model??null;
10
+ const currentDefault=()=>defaultDraft===undefined?savedDefault():defaultDraft;
11
+ const dirty=()=>currentDefault()!==savedDefault()||draft!==null&&JSON.stringify([...draft].sort())!==JSON.stringify(selected().sort());
10
12
  const count=value=>!value?'—':value>=1000000?`${Number((value/1000000).toFixed(2))}M`:value>=1000?`${Number((value/1000).toFixed(1))}K`:String(value);
11
13
  const groupedModels=()=>{
12
14
  if(Array.isArray(state.model_groups))return state.model_groups;
@@ -25,29 +27,51 @@
25
27
  if(!busy)el('gemini-enabled').checked=state.enabled;
26
28
  el('gemini-save').disabled=busy||sharedPending||!dirty();el('gemini-cancel').disabled=busy||sharedPending||!dirty();
27
29
  words('gemini-save',busy&&pendingAction==='models'?'api_saving':'api_save');if(busy&&pendingAction==='models')el('gemini-save').setAttribute('aria-busy','true');else el('gemini-save').removeAttribute('aria-busy');
28
- words('gemini-draft-state',dirty()?'cap_unsaved':'cap_saved');
29
- words('gemini-route-state',!state.enabled?'gemini_disabled':state.source_enabled===false?'gemini_source_disabled':state.app.status==='starting'?'gemini_route_waiting':state.models_reload_required===null?'gemini_catalog_unknown':state.models_reload_required?'gemini_models_pending':state.route_observed?'gemini_route_observed':'gemini_route_waiting');
30
+ el('gemini-draft-state').hidden=dirty()||!showSaved||state.app.status==='running'&&(state.models_reload_required===true||sharedApplication?.needs_reload===true);
31
+ if(!el('gemini-draft-state').hidden)words('gemini-draft-state','cap_saved');
32
+ el('gemini-use-app-default').hidden=currentDefault()===null;
33
+ el('gemini-default-note').hidden=!state.default_model_unavailable||currentDefault()!==savedDefault();
34
+ if(!el('gemini-default-note').hidden)words('gemini-default-note','gemini_default_unavailable');
35
+ const fallback=!globalThis.ccdxApplicationControls;
36
+ const sourceDisabled=state.enabled&&state.source_enabled===false;
37
+ el('gemini-route-state').hidden=!sourceDisabled;
38
+ if(sourceDisabled)words('gemini-route-state','gemini_source_disabled');
30
39
  el('gemini-version').textContent=state.app.version||'—';
31
- words('gemini-app-state',state.app.status==='running'?'gemini_running':state.app.status==='stopped'?'gemini_stopped':state.app.status==='starting'?'gemini_starting':'gemini_unavailable');
32
- const needsReload=state.enabled&&state.source_enabled!==false&&(state.models_reload_required===true||state.models_reload_required===null);
33
- const hint=!state.enabled&&state.app.status==='running'?'gemini_pause_reopen':needsReload?(state.app.status==='running'?(state.models_reload_required===null?'gemini_maybe_reopen':'gemini_reopen'):state.app.status==='stopped'?'gemini_open_to_load':null):null;
34
- el('gemini-reopen').hidden=!hint;if(hint)words('gemini-reopen',hint);
40
+ el('gemini-app-state').hidden=!fallback;
41
+ if(fallback)words('gemini-app-state',state.app.status==='running'?'gemini_running':state.app.status==='stopped'?'gemini_stopped':state.app.status==='starting'?'gemini_starting':'gemini_unavailable');
42
+ const hint=fallback&&state.app.status==='running'&&(!state.enabled||state.models_reload_required===true);
43
+ el('gemini-reopen').hidden=!hint;if(hint)words('gemini-reopen',state.enabled?'gemini_reopen':'gemini_pause_reopen');
44
+ el('gemini-open').hidden=!fallback;
35
45
  el('gemini-open').disabled=busy||sharedPending||state.app.status!=='stopped';
36
- const list=el('gemini-models'),focus=list.contains(document.activeElement)?document.activeElement.value:null;list.replaceChildren();
46
+ const list=el('gemini-models'),focused=list.contains(document.activeElement)?document.activeElement:null;
47
+ const focus={value:focused?.value,kind:focused?.tagName};list.replaceChildren();
37
48
  for(const model of groupedModels()){
38
49
  const chosen=new Set(draft||selected()),ids=model.efforts.map(item=>item.id);
39
50
  const row=document.createElement('tr'),name=document.createElement('td'),label=document.createElement('label'),input=document.createElement('input');
40
- input.type='checkbox';input.value=model.id;input.checked=ids.some(id=>chosen.has(id));input.disabled=busy;input.setAttribute('aria-label',model.name);
41
- const update=(values,checked)=>{const next=new Set(draft||selected());for(const id of values)if(checked)next.add(id);else next.delete(id);draft=[...next];notice=null;clear('gemini-note');render()};
51
+ input.type='checkbox';input.value=model.id;input.checked=ids.some(id=>chosen.has(id));input.disabled=busy||sharedPending;input.setAttribute('aria-label',model.name);
52
+ const update=(values,checked)=>{const next=new Set(draft||selected());for(const id of values)if(checked)next.add(id);else next.delete(id);draft=[...next];if(!checked&&values.includes(currentDefault()))defaultDraft=null;notice=null;clear('gemini-note');render()};
42
53
  input.addEventListener('change',()=>{const saved=ids.filter(id=>selected().includes(id));update(input.checked&&saved.length?saved:ids,input.checked)});
43
54
  label.append(input,document.createTextNode(model.name));name.append(label);row.append(name);
44
55
  for(const [key,value]of [['source','GitHub Copilot'],['cap_context',count(model.context_window)]]){const cell=document.createElement('td');cell.textContent=value;cell.dataset.label=language.format(key);row.append(cell)}
45
56
  const efforts=document.createElement('td');efforts.dataset.label=language.format('cap_reasoning');
46
57
  efforts.textContent=model.efforts.map(item=>item.effort||'—').join(' / ');
47
- row.append(efforts);list.append(row);
58
+ const preferred=document.createElement('td'),button=document.createElement('button');preferred.dataset.label=language.format('gemini_new_chat_default');
59
+ const isDefault=ids.includes(currentDefault())&&chosen.has(currentDefault());
60
+ button.type='button';button.value=model.id;button.disabled=busy||sharedPending;
61
+ const title=isDefault?'cap_default':'cap_set_default';language.set(button,title);
62
+ button.setAttribute('aria-pressed',String(isDefault));button.setAttribute('aria-label',model.name+' · '+language.format(title));
63
+ button.addEventListener('click',()=>{
64
+ if(isDefault)return;
65
+ const saved=ids.filter(id=>selected().includes(id)),visible=model.efforts.filter(item=>chosen.has(item.id));
66
+ const available=visible.length?visible:saved.length?model.efforts.filter(item=>saved.includes(item.id)):model.efforts;
67
+ if(!visible.length){for(const item of available)chosen.add(item.id);draft=[...chosen];}
68
+ defaultDraft=(available.find(item=>item.effort==='medium')||available[0])?.id??null;
69
+ notice=null;clear('gemini-note');render();
70
+ });
71
+ preferred.append(button);row.append(efforts,preferred);list.append(row);
48
72
  }
49
- if(!state.models.length){const row=document.createElement('tr'),cell=document.createElement('td');cell.colSpan=4;language.set(cell,'gemini_no_models');row.append(cell);list.append(row)}
50
- if(focus)[...list.querySelectorAll('input')].find(input=>input.value===focus)?.focus();
73
+ if(!state.models.length){const row=document.createElement('tr'),cell=document.createElement('td');cell.colSpan=5;language.set(cell,'gemini_no_models');row.append(cell);list.append(row)}
74
+ if(focus.kind)[...list.querySelectorAll(focus.kind.toLowerCase())].find(control=>control.value===focus.value)?.focus();
51
75
  for(const id of ['active','failed','copilot','total'])el('gemini-'+id).textContent=state.activity?.[id]??'—';
52
76
  if(notice)words('gemini-note',notice);
53
77
  }
@@ -57,7 +81,9 @@
57
81
  try{
58
82
  const write=action&&action!=='summary',response=await fetch('/_ccdx/ui/gemini'+(action==='summary'?'?scope=summary':''),{method:write?'POST':'GET',headers:{'X-CCDX-Dashboard':'1',...(write?{'Content-Type':'application/json'}:{})},cache:'no-store',signal:AbortSignal.timeout(20000),...(write?{body:JSON.stringify({action,...(action==='enable'?{accept_background_copilot:true}:{}),...extra})}:{})});
59
83
  const value=await response.json();if(!response.ok)throw Error(value.error||'Antigravity setup failed');
60
- state=value;if(action==='models')draft=null;
84
+ state=value;if(action==='models'){
85
+ draft=null;defaultDraft=undefined;showSaved=true;clearTimeout(savedTimer);savedTimer=setTimeout(()=>{showSaved=false;render()},2200);
86
+ }
61
87
  globalThis.ccdxGeminiStatus=state;
62
88
  if(action&&action!=='summary'){
63
89
  const status=state.last_operation?.status;notice=action==='models'?null:status==='needs_app_relaunch'?'gemini_reopen':status==='opened'?'gemini_opened':status==='route_conflict'?'gemini_conflict':null;
@@ -65,12 +91,13 @@
65
91
  }
66
92
  return state;
67
93
  }catch(error){if(!report)throw error;notice='gemini_operation_failed';words('gemini-note',notice);el('gemini-note').title=error.message}
68
- finally{busy=false;pendingAction=null;render();window.dispatchEvent(new CustomEvent('ccdx-gemini-state',{detail:{application:state?.application}}))}
94
+ finally{busy=false;pendingAction=null;render();window.dispatchEvent(new CustomEvent('ccdx-gemini-state',{detail:{application:state?.application,needsCatalogReload:state?.enabled===true&&state.source_enabled!==false&&state.models_reload_required===true&&state.default_model_unavailable!==true}}))}
69
95
  }
70
- globalThis.ccdxAntigravity={get state(){return state},get pending(){return busy},setEnabled:enabled=>load(enabled?'enable':'disable',{},false)};
96
+ globalThis.ccdxAntigravity={get state(){return state},get pending(){return busy},refreshStatus:()=>load('summary'),setEnabled:enabled=>load(enabled?'enable':'disable',{},false)};
71
97
  el('gemini-enabled').addEventListener('change',event=>void load(event.target.checked?'enable':'disable'));
72
- el('gemini-model-form').addEventListener('submit',event=>{event.preventDefault();if(dirty())void load('models',{models:draft})});
73
- el('gemini-cancel').addEventListener('click',()=>{draft=null;notice=null;clear('gemini-note');render()});
98
+ el('gemini-model-form').addEventListener('submit',event=>{event.preventDefault();if(dirty())void load('models',{models:draft||selected(),...(defaultDraft!==undefined?{default_model:defaultDraft}:{})})});
99
+ el('gemini-cancel').addEventListener('click',()=>{draft=null;defaultDraft=undefined;notice=null;clear('gemini-note');render()});
100
+ el('gemini-use-app-default').addEventListener('click',()=>{defaultDraft=null;render();el('gemini-save').focus();});
74
101
  el('gemini-open').addEventListener('click',()=>{if(globalThis.ccdxApplicationControls)globalThis.ccdxApplicationControls.open('antigravity');else void load('open')});
75
102
  window.addEventListener('ccdx:application-state',event=>{if(event.detail?.id==='antigravity'){sharedApplication=event.detail.application;sharedPending=event.detail.pending;render()}});
76
103
  el('gemini-refresh').addEventListener('click',()=>void load('refresh'));
@@ -176,11 +176,12 @@
176
176
  <div data-view="gemini" hidden>
177
177
  <section class="connection-access"><div class="connection-row"><label for="gemini-enabled" data-i18n="gemini_access_title">Copilot access</label><label class="switch-hit"><input id="gemini-enabled" type="checkbox" role="switch" data-i18n-label="gemini_access_title" aria-label="Copilot access" disabled></label></div></section>
178
178
  <section class="panel dashboard-section">
179
- <div class="panel-heading"><h2 data-i18n="cap_visible_model">Available models</h2><span id="gemini-draft-state" role="status">—</span></div>
179
+ <div class="panel-heading"><h2 data-i18n="cap_visible_model">Available models</h2><span id="gemini-draft-state" role="status" hidden></span></div>
180
180
  <form id="gemini-model-form">
181
- <div class="table-wrap"><table class="binding-table"><thead><tr><th data-i18n="model">Model</th><th data-i18n="source">Source</th><th data-i18n="cap_context">Context</th><th data-i18n="cap_reasoning">Reasoning</th></tr></thead><tbody id="gemini-models"></tbody></table></div>
182
- <div class="section-actions"><button id="gemini-save" type="submit" data-i18n="api_save" disabled>Save</button><button id="gemini-cancel" type="button" data-i18n="cap_discard_changes" disabled>Discard changes</button></div>
181
+ <div class="table-wrap"><table class="binding-table"><thead><tr><th data-i18n="model">Model</th><th data-i18n="source">Source</th><th data-i18n="cap_context">Context</th><th data-i18n="cap_reasoning">Reasoning</th><th data-i18n="gemini_new_chat_default">New chat default</th></tr></thead><tbody id="gemini-models"></tbody></table></div>
182
+ <div class="section-actions"><button id="gemini-save" type="submit" data-i18n="api_save" disabled>Save</button><button id="gemini-cancel" type="button" data-i18n="cap_discard_changes" disabled>Discard changes</button><button id="gemini-use-app-default" type="button" data-i18n="gemini_use_app_default" hidden>Use app default</button></div>
183
183
  </form>
184
+ <p id="gemini-default-note" class="hint" role="status" hidden></p>
184
185
  <p id="gemini-note" class="hint" role="status" aria-live="polite"></p>
185
186
  </section>
186
187
  <details class="panel dashboard-section" open>
@@ -189,7 +190,7 @@
189
190
  <p class="hint" data-i18n="gemini_scope">Native Google models remain available. Copilot models and background requests use Copilot.</p>
190
191
  <p id="gemini-app-state" class="table-note">—</p><p class="hint"><span data-i18n="gemini_version">Version</span>: <span id="gemini-version">—</span></p>
191
192
  <p id="gemini-reopen" class="hint" data-i18n="gemini_reopen" hidden>Quit Gemini, then open it here to load CCDX models.</p>
192
- <div class="section-actions"><button id="gemini-open" type="button" data-i18n="gemini_open">Open Antigravity</button><button id="gemini-refresh" type="button" data-i18n="refresh">Refresh</button><a class="section-link" href="#models" data-source-link="github">GitHub Copilot</a></div>
193
+ <div class="section-actions"><button id="gemini-open" type="button" data-i18n="gemini_open">Open Antigravity</button><button id="gemini-refresh" type="button" data-i18n="refresh">Refresh</button><a class="section-link" href="#models" data-source-link="github" data-i18n="gemini_open_sources">Model sources</a></div>
193
194
  </details>
194
195
  <details class="panel dashboard-section"><summary data-i18n="gemini_activity">Connection activity</summary>
195
196
  <p class="hint" data-i18n="gemini_activity_scope">Includes model requests and client discovery.</p>
@@ -414,18 +415,18 @@
414
415
  </div>
415
416
  <div data-view="system" hidden>
416
417
  <section class="panel dashboard-section" aria-labelledby="web-appearance-title">
417
- <h2 id="web-appearance-title" data-i18n="appearance_web_appearance">网页外观</h2>
418
+ <h2 id="web-appearance-title" data-i18n="appearance_web_appearance">Web appearance</h2>
418
419
  <div class="appearance-row">
419
- <div class="appearance-label"><label for="web-color-theme" data-i18n="appearance_color_theme">颜色主题</label><p id="web-color-note" role="status" data-i18n="theme_saved_browser">This browser only. Applies now.</p></div>
420
- <select id="web-color-theme" class="appearance-select"><option value="green" data-i18n="appearance_classic_green">经典绿(默认)</option><option value="klein" data-i18n="appearance_klein_blue">克莱因蓝</option><option value="pink" data-i18n="appearance_soft_pink">淡粉色</option><option value="mono" data-i18n="appearance_pure_white">纯白</option></select>
420
+ <div class="appearance-label"><label for="web-color-theme" data-i18n="appearance_color_theme">Color theme</label><p id="web-color-note" role="status" data-i18n="theme_saved_browser">This browser only. Applies now.</p></div>
421
+ <select id="web-color-theme" class="appearance-select"><option value="green" data-i18n="appearance_classic_green">Classic green (default)</option><option value="klein" data-i18n="appearance_klein_blue">Klein blue</option><option value="pink" data-i18n="appearance_soft_pink">Soft pink</option><option value="mono" data-i18n="appearance_pure_white">Pure white</option></select>
421
422
  </div>
422
423
  </section>
423
424
 
424
425
  <section class="panel dashboard-section" id="terminal-appearance" aria-labelledby="terminal-appearance-title">
425
- <h2 id="terminal-appearance-title" data-i18n="terminal_appearance">终端外观</h2>
426
+ <h2 id="terminal-appearance-title" data-i18n="terminal_appearance">Terminal appearance</h2>
426
427
  <div class="appearance-row">
427
- <div class="appearance-label"><label for="terminal-color-theme" data-i18n="appearance_color_theme">颜色主题</label><p id="terminal-color-note" role="status" data-i18n="appearance_terminal_effect">Table updates now; startup logo next launch.</p></div>
428
- <select id="terminal-color-theme" disabled class="appearance-select"><option value="green" data-i18n="appearance_classic_green">经典绿(默认)</option><option value="klein" data-i18n="appearance_klein_blue">克莱因蓝</option><option value="pink" data-i18n="appearance_soft_pink">淡粉色</option><option value="mono" data-i18n="appearance_black_white">黑白</option><option value="orange" data-i18n="appearance_orange">橙色</option></select>
428
+ <div class="appearance-label"><label for="terminal-color-theme" data-i18n="appearance_color_theme">Color theme</label><p id="terminal-color-note" role="status" data-i18n="appearance_terminal_effect">Table updates now; startup logo next launch.</p></div>
429
+ <select id="terminal-color-theme" disabled class="appearance-select"><option value="green" data-i18n="appearance_classic_green">Classic green (default)</option><option value="klein" data-i18n="appearance_klein_blue">Klein blue</option><option value="pink" data-i18n="appearance_soft_pink">Soft pink</option><option value="mono" data-i18n="appearance_black_white">Black &amp; white</option><option value="orange" data-i18n="appearance_orange">Orange</option></select>
429
430
  </div>
430
431
 
431
432
  <div class="setting-row terminal-animation-toggle"><label for="setting-terminal_animation_enabled" data-i18n="terminal_animation">Terminal animation</label><input id="setting-terminal_animation_enabled" type="checkbox" role="switch" disabled><span id="effect-terminal_animation_enabled" class="hint" role="status"></span></div>
@@ -46,11 +46,14 @@
46
46
  gemini_no_models: ["No Copilot models are listed. Check GitHub access in Model sources.", "暂无 Copilot 模型,请在模型来源页检查 GitHub 连接。"],
47
47
  gemini_version: ["Version", "版本"],
48
48
  gemini_disabled: ["Copilot access is paused", "Copilot 接入已停用"],
49
- gemini_source_disabled: ["GitHub Copilot source is disabled. Enable it in Model sources.", "GitHub Copilot 来源已停用,请到模型来源页启用。"],
49
+ gemini_source_disabled: ["Copilot source is off.", "Copilot 来源未启用。"],
50
+ gemini_open_sources: ["Model sources", "前往模型来源"],
51
+ gemini_new_chat_default: ["New chat default", "新会话默认"],
52
+ gemini_settings_saved: ["Model settings saved", "模型设置已保存"],
50
53
  gemini_scope: ["Native Google models keep their route. Copilot models and all Antigravity summaries, searches and images use Copilot. Ordinary Gemini chat keeps Google.", "原生 Google 模型保留原路由;Copilot 模型及全部 Antigravity 摘要、搜索和图像使用 Copilot。Gemini 普通聊天保留 Google。"],
51
54
  gemini_enable: ["Enable Copilot access", "启用 Copilot 接入"], gemini_disable: ["Pause Copilot access", "停用 Copilot 接入"], gemini_open: ["Open client", "打开客户端"],
52
- gemini_reopen: ["Quit Gemini when your work finishes, refresh its status, then open it here to reload CCDX models.", "请在任务完成后退出 Gemini,刷新状态后从这里打开,以加载 CCDX 模型。"],
53
- gemini_pause_reopen: ["Copilot access is paused. Quit Gemini, refresh its status, then open it here to restore its native Google route.", "Copilot 接入已停用。请退出 Gemini,刷新状态后从这里打开,以恢复原生 Google 路由。"],
55
+ gemini_reopen: ["Reopen the app to load the settings.", "重新打开应用以加载设置。"],
56
+ gemini_pause_reopen: ["Reopen the app to restore the Google route.", "重新打开应用以恢复 Google 接入。"],
54
57
  gemini_open_to_load: ["Open Gemini here to load CCDX models.", "请从这里打开 Gemini,以加载 CCDX 模型。"],
55
58
  gemini_opened: ["Client launch requested. Verify Antigravity access in the client.", "已请求打开客户端,请在 Antigravity 中确认接入。"],
56
59
  gemini_starting: ["Gemini is starting", "Gemini 正在启动"],
@@ -189,6 +192,9 @@
189
192
  "issue_model_not_selected": ["Model not selected for this app", "应用尚未选用此模型"],
190
193
  "issue_access_denied": ["Access was denied", "请求被拒绝访问"],
191
194
  "issue_request_failed": ["Request did not complete", "请求未完成"],
195
+ "issue_upstream_timeout": ["Source request timed out", "来源请求超时"],
196
+ "issue_after_send_timeout": ["Timed out waiting for the source", "等待来源响应超时"],
197
+ "issue_source_rate_wait": ["Source rate limit · wait {seconds} s", "来源限流 · 建议等待 {seconds} 秒"],
192
198
  "api_save_read": ["Save & read models", "保存并读取模型"],
193
199
  "api_read_failed": ["API saved. Model lookup failed; retry here. {code}", "来源已保存;模型读取失败,可在此重试。{code}"],
194
200
  "sync_capability_unverified": ["Client capabilities are unverified; existing settings were kept.", "客户端能力未验证,现有设置已保留。"],
@@ -406,6 +412,8 @@
406
412
  "ccdx_client_effort_unavailable": ["The saved reasoning level is unavailable. Choose a declared level or follow the app.", "已保存的推理档位不可用,请选择支持的档位或跟随应用。"],
407
413
  "cap_search": ["Search", "联网搜索"],
408
414
  "cap_default": ["Default", "默认"],
415
+ "gemini_use_app_default": ["Use app default", "使用应用默认"],
416
+ "gemini_default_unavailable": ["Choose a default model in the app.", "请在应用内选择默认模型。"],
409
417
  "cap_set_default": ["Set default", "设为默认"],
410
418
  "cap_details": ["Details", "能力详情"],
411
419
  "cap_app_access": ["App access", "应用接入"],
@@ -1019,7 +1027,18 @@
1019
1027
  "attempt_timings": ["Send attempts", "发送次数"],
1020
1028
  "body_queue_wait": ["Local queue history", "本机排队记录"],
1021
1029
  "source_queue_wait": ["Source queue", "来源排队"],
1022
- "body_queue_detail": ["Waited {ms} ms · {result}. At entry: {reason}. Reservation {reserved}; in use {occupied}/{limit}.", "等待 {ms} ms · {result}。入队原因:{reason}。预留 {reserved};入队时占用 {occupied}/{limit}。"],
1030
+ "upstream_request_sent": ["Send request", "请求发送耗时"],
1031
+ "upstream_body_written": ["Written to connection", "已交给连接"],
1032
+ "upstream_transport_error": ["Transport error", "传输错误"],
1033
+ "upstream_wait_headers": ["Wait for response headers", "等待响应头"],
1034
+ "request_total_time": ["Total time", "总耗时"],
1035
+ "request_masking": ["Local masking", "本地脱敏"],
1036
+ "request_total_inline": ["Total {value}", "总耗时 {value}"],
1037
+ "request_first_output": ["First usable output", "首个有效输出"],
1038
+ "client_request_id": ["Outbound request ID", "出站编号"],
1039
+ "retry_after": ["Retry-After", "重试提示"],
1040
+ "upstream_no_headers": ["Timed out before response headers", "等待响应头超时"],
1041
+ "body_queue_detail": ["{ms} ms · {result}. At entry: {reason}. Reserved {reserved}; in use {occupied}/{limit}.", "{ms} ms · {result}。{reason};预留 {reserved},占用 {occupied}/{limit}。"],
1023
1042
  "body_queue_admitted": ["Admitted", "已放行"],
1024
1043
  "body_queue_timed_out": ["Queue timed out", "排队超时"],
1025
1044
  "body_queue_aborted": ["Wait cancelled", "等待已取消"],
@@ -1194,7 +1213,7 @@
1194
1213
  "code": ["Error code", "错误代码"],
1195
1214
  "message": ["Error details", "错误详情"],
1196
1215
  "response_id": ["Response ID", "回答编号"],
1197
- "upstream_request_id": ["Source request ID", "来源编号"],
1216
+ "upstream_request_id": ["Source request ID", "来源返回编号"],
1198
1217
  "upstream_code": ["Source error code", "来源错误码"],
1199
1218
  "request_id": ["CCDX request ID", "本机编号"],
1200
1219
  "outcome_25a63": ["Result", "处理结果"],
@@ -100,6 +100,15 @@
100
100
  return days ? `${days}d ${hours}h` : hours ? `${hours}h ${minutes}m` : `${minutes}m`;
101
101
  }
102
102
 
103
+ const requestTime = ms => ms >= 1000 ? `${(ms / 1000).toFixed(2)} s` : `${number(ms)} ms`;
104
+ function retryAfterSeconds(failure) {
105
+ const value = failure.retry_after;
106
+ if (typeof value !== "string") return null;
107
+ if (/^\d{1,8}$/.test(value)) return Number(value) || null;
108
+ const seconds = Math.ceil((Date.parse(value) - Date.parse(failure.at)) / 1000);
109
+ return Number.isFinite(seconds) && seconds > 0 ? seconds : null;
110
+ }
111
+
103
112
  function renderFailures(recent, recentRequests = []) {
104
113
  if (!visible(element("failures"))) return;
105
114
  const signature = JSON.stringify([element("failure-kind")?.value, recent, recentRequests]);
@@ -144,6 +153,9 @@
144
153
  details.dataset.key = `${failure.at}/${failure.request_id || failure.response_id}/${failure.code}`;
145
154
  details.open = expanded.has(details.dataset.key);
146
155
  const title = document.createElement("summary");
156
+ const timeline = failure.timeline;
157
+ const attempt = (failure.attempt_timings || timeline?.attempts)?.at(-1);
158
+ const seconds = retryAfterSeconds(failure);
147
159
  const cause = failure.route === "messages_count_tokens" && [404, 405, 501].includes(failure.http_status) ? "issue_count_unavailable"
148
160
  : ["credit_balance_exhausted", "insufficient_quota", "quota_exceeded"].includes(failure.upstream_code) ? "issue_source_quota"
149
161
  : ["rate_limit_exceeded", "rate_limit_error"].includes(failure.upstream_code) ? "issue_source_rate"
@@ -152,12 +164,15 @@
152
164
  : ["rate_limit_error", "rate_limit_exceeded", "insufficient_quota", "http_429"].includes(failure.code) ? "issue_source_limit"
153
165
  : /^m365_catalog_http_/.test(failure.code || "") ? "issue_catalog_unavailable"
154
166
  : failure.reason === "ccdx_model_not_selected" ? "issue_model_not_selected"
155
- : failure.http_status === 401 || failure.http_status === 403 ? "issue_access_denied" : "issue_request_failed";
167
+ : failure.http_status === 429 && failure.origin === "upstream_http" ? "issue_source_rate"
168
+ : failure.http_status === 504 && failure.code === "upstream_timeout"
169
+ ? Number.isFinite(attempt?.body_sent_ms) && attempt.headers_ms === null ? "issue_after_send_timeout" : "issue_upstream_timeout"
170
+ : failure.http_status === 401 || failure.http_status === 403 ? "issue_access_denied" : "issue_request_failed";
156
171
  const summary = {
157
172
  detail: phrase("issue_brief", {
158
173
  time: failure.at ? time(failure.at, { date: true }) : phrase("unknown_time"),
159
174
  model: notModelRequest ? phrase("not_applicable") : failure.model ? String(failure.model).slice(0, 80) : phrase("unknown_model"),
160
- cause: phrase(cause),
175
+ cause: failure.http_status === 429 && failure.origin === "upstream_http" && seconds ? phrase("issue_source_rate_wait", { seconds: number(seconds) }) : phrase(cause),
161
176
  }),
162
177
  retry: phrase(failure.upstream_attempts === 0 ? "no_upstream_call" : failure.retried ? "retry_attempted" : "no_retry"),
163
178
  };
@@ -166,7 +181,6 @@
166
181
  summary.detail = phrase("repeated_issue", { detail: summary.detail, count: failure.occurrences });
167
182
  localize(title, "detail_retry", summary);
168
183
  }
169
- const timeline = failure.timeline;
170
184
  const provider = failure.provider || timeline?.provider;
171
185
  if (provider) {
172
186
  const source = sourceLabel(provider);
@@ -176,8 +190,10 @@
176
190
  const timings = timeline?.timings_ms || {};
177
191
  const timingText = ["admission", "body", "history", "images", "serialization", "upstream_start", "upstream_headers", "first_output", "last_activity", "terminal", "finished"]
178
192
  .filter((key) => finite(timings[key])).map((key) => `${key}=${Number(timings[key]).toFixed(1)}`).join(" / ");
179
- const fields = { time: failure.at, model: notModelRequest ? phrase("not_applicable") : failure.model, event: failure.event_type, code: failure.code, reason: failure.reason, application: failure.application, occurrences: failure.occurrences > 1 ? failure.occurrences : undefined, capability_cached: failure.capability_cached, shared_upstream: failure.shared_upstream,
180
- message: failure.message, response_id: failure.response_id, upstream_request_id: failure.upstream_request_id,
193
+ const fields = { time: failure.at, model: notModelRequest ? phrase("not_applicable") : failure.model, event: failure.event_type, code: failure.code, reason: failure.reason, application: failure.application === "gemini_app" ? phrase("flow_app_gemini_app") : failure.application, occurrences: failure.occurrences > 1 ? failure.occurrences : undefined, capability_cached: failure.capability_cached, shared_upstream: failure.shared_upstream,
194
+ message: failure.message, response_id: failure.response_id, client_request_id: attempt?.client_request_id,
195
+ upstream_request_id: failure.upstream_request_id, retry_after: failure.retry_after,
196
+ request_total_time: Number.isFinite(timings.finished) ? requestTime(timings.finished) : undefined,
181
197
  retry: failure.retried ? (timeline ? "attempted" : "attempted (outcome not recorded here)") : "not attempted",
182
198
  retry_policy: failure.retry_policy, retry_skipped: failure.retry_skipped,
183
199
  recovery: failure.recovery ? JSON.stringify(failure.recovery) : undefined,
@@ -189,7 +205,7 @@
189
205
  request_options: failure.request_options ? JSON.stringify(failure.request_options) : undefined,
190
206
  transport: failure.transport ? JSON.stringify(failure.transport) : undefined,
191
207
  output_requested: timeline?.context?.max_output_tokens_requested, output_sent: timeline?.context?.max_output_tokens_sent,
192
- output_used: timeline?.context?.output_tokens, stop_reason: timeline?.stop_reason, requested_model: failure.requested_model, request_kind: failure.request_kind, provider: failure.provider || timeline?.provider,
208
+ output_used: timeline?.context?.output_tokens, stop_reason: timeline?.stop_reason, requested_model: failure.requested_model, request_kind: failure.request_kind === "unknown" ? undefined : failure.request_kind, provider: failure.provider || timeline?.provider,
193
209
  attempt_timings: failure.attempt_timings || timeline?.attempts ? JSON.stringify(failure.attempt_timings || timeline.attempts) : undefined,
194
210
  timings_ms: timingText };
195
211
  const diagnostic = document.createElement("dl");
@@ -394,25 +410,38 @@
394
410
  } else if (globalThis.ccdxIcons) globalThis.ccdxIcons.set(row.children[3], wireFailure ? "request_http_failure" : outcome.toLowerCase(),
395
411
  wireFailure ? "warning" : globalThis.ccdxIcons.kind(outcome.toLowerCase()), wireFailure ? { status: request.http_status } : {});
396
412
  else if (wireFailure) localize(row.children[3], "request_http_failure", { status: request.http_status });
413
+ const totalMs = request.timings_ms?.finished;
414
+ if (Number.isFinite(totalMs)) {
415
+ const total = document.createElement("small");total.className = "table-note";
416
+ localize(total, "request_total_inline", { value: requestTime(totalMs) });row.children[3].append(total);
417
+ }
397
418
  const details = document.createElement("details"), summary = document.createElement("summary"), fields = document.createElement("dl");
398
419
  const key = String(request.request_id || `${request.at || ""}/${request.provider || ""}/${request.model || ""}`).slice(0, 256);
399
420
  details.setAttribute?.("data-request-key", key);details.open = expanded.has(key);
400
421
  details.className = "request-details";fields.className = "failure-detail";
401
- if (Number.isSafeInteger(context.privacy_count)) globalThis.ccdxLanguage.set(summary, "privacy_result", { count: context.privacy_count, ms: context.privacy_ms || 0 });
402
- else localize(summary, "request_metadata");details.append(summary, fields);
422
+ localize(summary, "tools_details");details.append(summary, fields);
403
423
  const queue = context.body_queue;
404
424
  const queueResult = queue?.outcome === "admitted" ? "body_queue_admitted" : queue?.outcome === "timed_out" ? "body_queue_timed_out"
405
425
  : queue?.outcome === "aborted" ? "body_queue_aborted" : "body_queue_result_unknown";
406
426
  const queueReason = queue?.reason === "upload_in_progress" ? "body_queue_upload_in_progress" : queue?.reason === "upload_growth" ? "body_queue_upload_growth"
407
427
  : queue?.reason === "exclusive_waiter" ? "body_queue_exclusive"
408
428
  : queue?.length_known === false && queue.requested_bytes === queue.limit_bytes ? "body_queue_unknown_length" : "body_queue_budget";
429
+ const attempt = request.attempts?.at(-1);
409
430
  for (const [key, value] of [["request_id", request.request_id || "—"], ["http_status", number(request.http_status)], ["attempts", number(request.upstream_attempts)], ["model_outcome", globalThis.ccdxLanguage?.format(outcome.toLowerCase()) || outcome],
410
431
  ["time", Number.isFinite(at) ? time(at, { date: true }) : "—"],
411
- ...(Number.isSafeInteger(queue?.wait_ms) ? [["body_queue_wait", phrase("body_queue_detail", {
432
+ ...(Number.isSafeInteger(queue?.wait_ms) && queue.wait_ms > 0 ? [["body_queue_wait", phrase("body_queue_detail", {
412
433
  ms: number(queue.wait_ms), result: phrase(queueResult), reason: phrase(queueReason),
413
434
  reserved: mib(queue.requested_bytes), occupied: mib(queue.active_bytes), limit: mib(queue.limit_bytes),
414
435
  })]] : []),
415
- ...(Number.isSafeInteger(context.source_queue_ms) ? [["source_queue_wait", `${number(context.source_queue_ms)} ms`]] : []),
436
+ ...(Number.isSafeInteger(context.source_queue_ms) && context.source_queue_ms > 0 ? [["source_queue_wait", `${number(context.source_queue_ms)} ms`]] : []),
437
+ ...(Number.isSafeInteger(attempt?.body_written_bytes) && !Number.isFinite(attempt.body_sent_ms) ? [["upstream_body_written", `${number(attempt.body_written_bytes)} / ${number(context.payload_bytes)} B`]] : []),
438
+ ...(attempt?.transport_error ? [["upstream_transport_error", attempt.transport_error]] : []),
439
+ ...(Number.isFinite(attempt?.body_sent_ms) ? [["upstream_request_sent", `${number(attempt.body_sent_ms - attempt.started_ms)} ms`]] : []),
440
+ ...(Number.isFinite(attempt?.body_sent_ms) && Number.isFinite(attempt.headers_ms) ? [["upstream_wait_headers", requestTime(Math.max(0, attempt.headers_ms - attempt.body_sent_ms))]]
441
+ : Number.isFinite(attempt?.body_sent_ms) && attempt.headers_ms === null && request.origin === "transport" && request.http_status === 504 ? [["upstream_wait_headers", phrase("upstream_no_headers")]] : []),
442
+ ...(Number.isFinite(request.timings_ms?.first_output) ? [["request_first_output", requestTime(request.timings_ms.first_output)]] : []),
443
+ ...(attempt?.client_request_id ? [["client_request_id", attempt.client_request_id]] : []),
444
+ ...(Number.isSafeInteger(context.privacy_count) ? [["request_masking", phrase("privacy_result", { count: context.privacy_count, ms: context.privacy_ms || 0 })]] : []),
416
445
  ["wire_mib", finite(context.payload_bytes) ? `${(Number(context.payload_bytes) / 1048576).toFixed(2)} MiB` : "—"],
417
446
  ["images", number(context.images)], ["model_window", number(context.context_window_tokens)], ["input_window", ratio],
418
447
  ["output_requested", number(context.max_output_tokens_requested)], ["output_sent", number(context.max_output_tokens_sent)], ["output_used", number(context.output_tokens)], ["stop_reason", request.stop_reason || "—"],
@@ -38,7 +38,7 @@ button[aria-busy="true"] { cursor: progress; }
38
38
  h1 { margin: 0; font-size: clamp(20px, 3vw, 27px); font-weight: 650; letter-spacing: -.035em; }
39
39
  .status-icon { display: block; grid-row: 1 / 3; width: 44px; height: 44px; color: var(--accent); }
40
40
  .intro p { margin: 0; color: var(--subtle); font-size: 11px; }
41
- .intro.has-application-launch { align-items:center; flex-wrap:wrap; }
41
+ .intro.has-application-launch { display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px; }
42
42
  .intro.has-application-launch #page-settings-note { order:3; flex-basis:100%; }
43
43
  .intro.has-application-launch #page-settings-note:empty { display:none; }
44
44
  #application-launch { display:flex; flex-direction:column; align-items:flex-end; gap:5px; margin-left:auto; }
@@ -305,6 +305,7 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
305
305
  .analytics-controls select { box-sizing: border-box; height:var(--control-height); min-height:var(--control-height); line-height:normal; }
306
306
  .section-actions button, .section-actions .button-link { padding-top: 0; padding-bottom: 0; }
307
307
  @media (max-width: 640px) {
308
+ .sidebar nav .nav-child { padding-left: 10px; }
308
309
  .topbar { height:auto; min-height:96px; padding:8px 0; }
309
310
  .topbar-actions { display:flex; flex-wrap:wrap; justify-content:flex-start; gap:8px; }
310
311
  .topbar-actions #connection { flex-basis:100%; }
@@ -4,6 +4,8 @@ import { isProviderId } from "./provider-metadata.mjs";
4
4
  import { transportErrorDetails } from "./operation-error.mjs";
5
5
  import { safeUpstreamReason } from "./safe-upstream-error.mjs";
6
6
 
7
+ import { upstreamRetryAfter } from "./upstream-headers.mjs";
8
+
7
9
  const DEFAULT_RECENT_FAILURES = 10;
8
10
 
9
11
  function safeIdentifier(value, fallback = "unknown") {
@@ -159,7 +161,7 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
159
161
  all.record(details);
160
162
  const accessNotice = details.reason === "ccdx_model_not_selected" || details.reason === "ccdx_client_source_disabled";
161
163
  const category = accessNotice || details.route === "messages_count_tokens" ? "capability"
162
- : ["responses", "responses_compact", "messages"].includes(details.route) ? "inference"
164
+ : ["responses", "responses_compact", "messages", "antigravity"].includes(details.route) ? "inference"
163
165
  : details.route === "image_mcp" && details.http_status === 405 ? "protocol"
164
166
  : details.route === "not_found" ? "route" : "other";
165
167
  counts[category]++;
@@ -208,7 +210,9 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
208
210
  : error_body === "empty" ? "Upstream returned no error details." : "HTTP request failed; original response was preserved.");
209
211
  const details = responseFailureDetails({ model, error: { code: typeof code === "string" && /^[a-z\d_.:-]{1,80}$/i.test(code) ? code : `http_${statusCode}`,
210
212
  message: model_error ? "The model source reported an error; the original HTTP response was preserved." : message } }, model_error ? "model.error" : "http.error", { headers, provider });
213
+ const retryAfter = origin === "upstream_http" && [429, 503].includes(statusCode) ? upstreamRetryAfter(headers) : null;
211
214
  return { ...details, request_id: requestId, http_status: statusCode, route,
215
+ ...(retryAfter === null ? {} : { retry_after: retryAfter }),
212
216
  origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true,
213
217
  ...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}),
214
218
  ...(safeUpstreamReason(upstream_code, statusCode) ? { upstream_code } : {}), ...(parameter ? { parameter } : {}),
@@ -217,7 +221,7 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
217
221
  ...(request_options ? { request_options } : {}),
218
222
  ...(attempt_timings ? { attempt_timings } : {}),
219
223
  ...(requested_model ? { requested_model, request_kind: requested_model === "codex-auto-review" ? "auto_review" : "unknown" } : {}),
220
- ...(["codex_app", "codex_cli", "codex", "claude_app", "claude_code", "claude", "api"].includes(application) ? { application } : {}),
224
+ ...(["codex_app", "codex_cli", "codex", "claude_app", "claude_code", "claude", "gemini_app", "api"].includes(application) ? { application } : {}),
221
225
  ...(Object.hasOwn(reasons, reason) ? { reason } : {}),
222
226
  ...(capability_cached === true ? { capability_cached: true } : {}), ...(shared_upstream === true ? { shared_upstream: true } : {}),
223
227
  ...(transport ? { transport: transportErrorDetails({ transport }) } : {}),
@@ -86,8 +86,11 @@ function emptyReasoningItem(item) {
86
86
  && Object.keys(item).every(key => ["type", "id", "status", "summary", "content", "encrypted_content"].includes(key));
87
87
  }
88
88
 
89
+ const isEmptyUser = message => message.role === "user" && (message.content === "" || Array.isArray(message.content) && message.content.length === 0);
90
+
89
91
  export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
90
92
  const messages = [];
93
+ let emptyUserPlaceholder = false;
91
94
  if (body.instructions) messages.push({ role: "system", content: body.instructions });
92
95
 
93
96
  const cacheFields = value => {
@@ -134,7 +137,9 @@ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
134
137
  && ["user", "assistant", "system", "developer"].includes(item?.role)
135
138
  && Object.prototype.hasOwnProperty.call(item, "content");
136
139
  if (item?.type === "message" || isEasyMessage) {
137
- messages.push({ role: item.role, content: messageContent(item.content, item) });
140
+ const message = { role: item.role, content: messageContent(item.content, item) };
141
+ if (isEmptyUser(message)) emptyUserPlaceholder = true;
142
+ messages.push(message);
138
143
  } else if (item?.type === "agent_message") {
139
144
  if (typeof item.author !== "string" || typeof item.recipient !== "string" || !Array.isArray(item.content) || item.encrypted_content != null) {
140
145
  throw chatCompatibilityError("input item", "agent_message");
@@ -195,7 +200,10 @@ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
195
200
  }
196
201
  }
197
202
 
198
- const chatReq = { model: body.model, messages, stream: true };
203
+ // A media placeholder can be empty after Codex compaction. Preserve lone
204
+ // empty input for provider validation, and keep images and cache markers.
205
+ const omitPlaceholders = emptyUserPlaceholder && messages.some(message => message.role === "user" && message.content !== null && !isEmptyUser(message));
206
+ const chatReq = { model: body.model, messages: omitPlaceholders ? messages.filter(message => !isEmptyUser(message)) : messages, stream: true };
199
207
  for (const k of ["temperature", "top_p", "stop", "presence_penalty", "frequency_penalty"]) {
200
208
  if (body[k] !== undefined) chatReq[k] = body[k];
201
209
  }
@@ -14,6 +14,6 @@ export function sourceTransport(options, input) {
14
14
  const context = options[SOURCE_HTTP_CONTEXT];
15
15
  if (!context || options.countTokens) return send(input);
16
16
  return context.scheduler.run(context.descriptor(), send, { args: input, signal: options.signal,
17
- model: input.model, client: currentRequestContext()?.application || "other", bodyText: input.bodyText,
17
+ model: input.model, client: currentRequestContext()?.application || "other", bodyText: input.bodyText, bytes: input.bodyBytes,
18
18
  sourceBodyManaged: options.sourceBodyManaged === true });
19
19
  }
@@ -287,7 +287,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
287
287
  changes.changed();
288
288
  };
289
289
 
290
- return {
290
+ const tracker = {
291
291
  beginStage(stage) {
292
292
  const histogram = route.preparation[stage];
293
293
  if (!histogram || finished) return null;
@@ -473,6 +473,21 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
473
473
  else route.success_with_output += 1;
474
474
  },
475
475
  };
476
+ if (routeName === "antigravity") tracker.observeUpstreamBodyWrite = clientRequestId => {
477
+ const attempt = attemptTimings.at(-1);
478
+ if (!attempt || finished) return;
479
+ return (kind, value) => {
480
+ if (finished) return;
481
+ if (kind === "start") {
482
+ attempt.body_written_bytes ??= 0;
483
+ if (typeof clientRequestId === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(clientRequestId)) attempt.client_request_id = clientRequestId;
484
+ }
485
+ if (kind === "chunk") attempt.body_written_bytes = (attempt.body_written_bytes || 0) + value;
486
+ if (kind === "sent") attempt.body_sent_ms ??= elapsed(now());
487
+ if (kind === "error") attempt.transport_error ??= value;
488
+ };
489
+ };
490
+ return tracker;
476
491
  },
477
492
  contextSnapshot: () => contexts.snapshot(),
478
493
  activitySnapshot() {
@@ -530,6 +545,10 @@ export function markUpstreamStarted(streaming = true) {
530
545
  tracker()?.upstreamStarted(streaming);
531
546
  }
532
547
 
548
+ export function observeUpstreamBodyWrite(clientRequestId) {
549
+ return tracker()?.observeUpstreamBodyWrite?.(clientRequestId);
550
+ }
551
+
533
552
  export function markUpstreamHeaders(statusCode) {
534
553
  tracker()?.upstreamHeaders?.(statusCode);
535
554
  }
@@ -27,6 +27,29 @@ function headerValue(headers, name) {
27
27
  return typeof value === "string" && value.trim() ? value : null;
28
28
  }
29
29
 
30
+ // Keep only a valid delay or an HTTP-date from an upstream rejection.
31
+ export function upstreamRetryAfter(headers) {
32
+ const value = headerValue(headers, "retry-after")?.trim();
33
+ if (!value) return null;
34
+ if (/^\d{1,8}(?:\.\d{1,3})?$/.test(value)) return String(Math.ceil(Number(value)));
35
+ if (!/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(value)) return null;
36
+ const parsed = Date.parse(value);
37
+ return Number.isFinite(parsed) && new Date(parsed).toUTCString() === value ? value : null;
38
+ }
39
+
40
+ export function upstreamRejectionHeaders(status, headers) {
41
+ const out = new Headers();
42
+ if (status === 429 || status === 503) {
43
+ const retry = upstreamRetryAfter(headers);
44
+ if (retry !== null) out.set("Retry-After", retry);
45
+ }
46
+ for (const name of REQUEST_ID_HEADERS) {
47
+ const id = headerValue(headers, name)?.trim();
48
+ if (/^[A-Za-z0-9._:/-]{1,160}$/.test(id || "")) { out.set(name, id);break; }
49
+ }
50
+ return out;
51
+ }
52
+
30
53
  function canonicalHeaderName(name) {
31
54
  return String(name).split("-").map((part) => (
32
55
  part ? `${part[0].toUpperCase()}${part.slice(1).toLowerCase()}` : part