codex-copilot-dx 1.4.8 → 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 +4 -4
- package/package.json +1 -1
- package/src/antigravity-handler.mjs +34 -11
- package/src/antigravity-runtime.mjs +1 -1
- package/src/application-configuration.mjs +1 -1
- package/src/copilot-client.mjs +6 -4
- package/src/copilot-send-timing.mjs +63 -0
- package/src/copilot.mjs +5 -1
- package/src/dashboard/applications.js +9 -5
- package/src/dashboard/gemini.js +18 -11
- package/src/dashboard/index.html +3 -3
- package/src/dashboard/language.js +24 -7
- package/src/dashboard/status.js +39 -10
- package/src/response-failures.mjs +6 -2
- package/src/responses-bridge.mjs +10 -2
- package/src/source-transport.mjs +1 -1
- package/src/stream-performance.mjs +20 -1
- package/src/upstream-headers.mjs +23 -0
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
|
-
|
|
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
|
|
|
@@ -257,9 +257,9 @@ For an identified conversation, hovering a point in the input-history chart show
|
|
|
257
257
|
|
|
258
258
|
## Shared source concurrency
|
|
259
259
|
|
|
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.
|
|
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`.
|
|
261
261
|
|
|
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.
|
|
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.
|
|
263
263
|
|
|
264
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.
|
|
265
265
|
|
|
@@ -855,7 +855,7 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
|
|
|
855
855
|
| `CCDX_DISABLE_USAGE` | unset | Set to `1` to disable usage logging |
|
|
856
856
|
| `CCDX_SHUTDOWN_TIMEOUT_MS` | `5000` | Time to drain active HTTP connections before forcing shutdown |
|
|
857
857
|
|
|
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.
|
|
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.
|
|
859
859
|
|
|
860
860
|
## Usage logging
|
|
861
861
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
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
8
|
import {ANTIGRAVITY_MODEL_PREFIX,antigravityCopilotModels,hasAntigravityAgentDefault,mergeAntigravityModels} from "./antigravity-models.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
|
|
|
@@ -40,10 +45,11 @@ function groundedSearch(result,query){
|
|
|
40
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");
|
|
48
|
+
const acquireControl=createRequestAdmission({maxBytes:4*CONTROL_BODY_BYTES,maxQueued:8});
|
|
43
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
|
-
|
|
81
|
-
|
|
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,{
|
|
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);
|
|
@@ -203,7 +212,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
203
212
|
converted=antigravityToChat(request,{model:target.model,effort:target.effort,reasoningEfforts:target.effort?[target.effort]:[],stream});
|
|
204
213
|
markResponseModel(target.model);markRequestObservation({usage_state:"pending"});
|
|
205
214
|
session=privacy?.prepareSession?await privacy.prepareSession(converted.chat,{protocol:"chat",client:"gemini",signal:abort.signal}):passthrough(converted.chat);
|
|
206
|
-
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")};
|
|
207
216
|
phase="upstream";
|
|
208
217
|
const upstream=compacting&&compaction?await compaction.run({body:session.body,protocol:"chat",scope:JSON.stringify(["gemini","github",compactionProfile()]),source:"github",client:"gemini",
|
|
209
218
|
inputLimit:target.maxTokens,outputAllowance:session.body.max_completion_tokens||session.body.max_tokens||0,native:client.chatCompletions,options:callOptions,
|
|
@@ -211,13 +220,23 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
211
220
|
releaseInput();
|
|
212
221
|
markUpstreamHeaders(upstream.status);
|
|
213
222
|
applicationEvidence?.accept(req,"antigravity","inference");
|
|
214
|
-
if(!upstream.ok){
|
|
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
|
+
}
|
|
215
229
|
if(!stream){
|
|
216
230
|
const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));captureUsage(data);
|
|
217
231
|
const result=chatToAntigravity(data,converted.originalNames);markToolActivity(result,"gemini");
|
|
218
232
|
outcome=result.candidates[0].finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome);
|
|
219
233
|
res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response:session.restoreValue(result)}));return;
|
|
220
234
|
}
|
|
235
|
+
if (!upstream.body) {
|
|
236
|
+
sourceResponseFailed(upstream);
|
|
237
|
+
markResponseErrorOrigin("upstream_event");
|
|
238
|
+
throw httpError("Upstream Chat stream has no body",502);
|
|
239
|
+
}
|
|
221
240
|
const text=session.count?createPrivacyTextFragments(session):{push:value=>value,finish:()=>""};
|
|
222
241
|
res.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache"});
|
|
223
242
|
const emit=chunk=>writeOrDrain(res,"data: "+JSON.stringify(chunk)+"\n\n",{signal:abort.signal});
|
|
@@ -246,7 +265,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
246
265
|
if(res.headersSent&&!res.writableEnded&&!res.destroyed){res.end("data: "+JSON.stringify({error:{code:error.statusCode||502,message:error.message}})+"\n\n");}
|
|
247
266
|
else sendJsonError(res,error,error.statusCode||502);
|
|
248
267
|
}finally{
|
|
249
|
-
releaseInput();session?.release();abort.cleanup();active--;
|
|
268
|
+
releaseInput();releaseControl?.();session?.release();abort.cleanup();active--;
|
|
250
269
|
if(usageEvent){
|
|
251
270
|
const u=usageEvent.usage,record=buildResponsesUsageRecord({surface:"antigravity",mode:usageMode,model:usageModel,
|
|
252
271
|
response:{id:usageEvent.id,model:usageEvent.model||usageModel,usage:u?{input_tokens:u.prompt_tokens,output_tokens:u.completion_tokens,
|
|
@@ -261,6 +280,10 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
261
280
|
}
|
|
262
281
|
}
|
|
263
282
|
};
|
|
264
|
-
handler.snapshot=()=>
|
|
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
|
+
};
|
|
265
288
|
return handler;
|
|
266
289
|
}
|
|
@@ -76,7 +76,7 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
|
|
|
76
76
|
const defaultUnavailable=config.default_model!==null&&(!desiredDefault||activity.catalog_default_supported===false);
|
|
77
77
|
const current=applicationControl?.snapshot().antigravity;
|
|
78
78
|
const visibleApp=current?{status:current.status,version:current.version||null,pids:current.pid?[current.pid]:[]}:app;
|
|
79
|
-
return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,default_model_unavailable:defaultUnavailable,models_reload_required:reload,app:visibleApp,application:current||null,route_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,
|
|
80
80
|
model_source:"Google + GitHub Copilot",background_source:"GitHub Copilot",ordinary_chat_source:"Google (unchanged)",
|
|
81
81
|
compaction_source:"Observed conversation source; existing background policy when unassigned",
|
|
82
82
|
models:listed,model_groups:[...groups.values()],activity,last_operation:lastOperation};
|
|
@@ -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;
|
package/src/copilot-client.mjs
CHANGED
|
@@ -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
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
|
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
|
|
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
|
|
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")
|
|
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
|
|
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) };
|
package/src/dashboard/gemini.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
const el=id=>document.getElementById(id),language=globalThis.ccdxLanguage;
|
|
3
3
|
let busy=false,state=null,draft=null,defaultDraft,notice=null,pendingAction=null;
|
|
4
|
-
let sharedApplication=null,sharedPending=false;
|
|
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
7
|
const controls=['gemini-enabled','gemini-open','gemini-refresh','gemini-save','gemini-cancel','gemini-use-app-default'];
|
|
@@ -27,16 +27,21 @@
|
|
|
27
27
|
if(!busy)el('gemini-enabled').checked=state.enabled;
|
|
28
28
|
el('gemini-save').disabled=busy||sharedPending||!dirty();el('gemini-cancel').disabled=busy||sharedPending||!dirty();
|
|
29
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');
|
|
30
|
-
|
|
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');
|
|
31
32
|
el('gemini-use-app-default').hidden=currentDefault()===null;
|
|
32
33
|
el('gemini-default-note').hidden=!state.default_model_unavailable||currentDefault()!==savedDefault();
|
|
33
34
|
if(!el('gemini-default-note').hidden)words('gemini-default-note','gemini_default_unavailable');
|
|
34
|
-
|
|
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');
|
|
35
39
|
el('gemini-version').textContent=state.app.version||'—';
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const hint
|
|
39
|
-
el('gemini-reopen').hidden=!hint;if(hint)words('gemini-reopen',
|
|
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;
|
|
40
45
|
el('gemini-open').disabled=busy||sharedPending||state.app.status!=='stopped';
|
|
41
46
|
const list=el('gemini-models'),focused=list.contains(document.activeElement)?document.activeElement:null;
|
|
42
47
|
const focus={value:focused?.value,kind:focused?.tagName};list.replaceChildren();
|
|
@@ -50,7 +55,7 @@
|
|
|
50
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)}
|
|
51
56
|
const efforts=document.createElement('td');efforts.dataset.label=language.format('cap_reasoning');
|
|
52
57
|
efforts.textContent=model.efforts.map(item=>item.effort||'—').join(' / ');
|
|
53
|
-
const preferred=document.createElement('td'),button=document.createElement('button');preferred.dataset.label=language.format('
|
|
58
|
+
const preferred=document.createElement('td'),button=document.createElement('button');preferred.dataset.label=language.format('gemini_new_chat_default');
|
|
54
59
|
const isDefault=ids.includes(currentDefault())&&chosen.has(currentDefault());
|
|
55
60
|
button.type='button';button.value=model.id;button.disabled=busy||sharedPending;
|
|
56
61
|
const title=isDefault?'cap_default':'cap_set_default';language.set(button,title);
|
|
@@ -76,7 +81,9 @@
|
|
|
76
81
|
try{
|
|
77
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})}:{})});
|
|
78
83
|
const value=await response.json();if(!response.ok)throw Error(value.error||'Antigravity setup failed');
|
|
79
|
-
state=value;if(action==='models'){
|
|
84
|
+
state=value;if(action==='models'){
|
|
85
|
+
draft=null;defaultDraft=undefined;showSaved=true;clearTimeout(savedTimer);savedTimer=setTimeout(()=>{showSaved=false;render()},2200);
|
|
86
|
+
}
|
|
80
87
|
globalThis.ccdxGeminiStatus=state;
|
|
81
88
|
if(action&&action!=='summary'){
|
|
82
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;
|
|
@@ -84,9 +91,9 @@
|
|
|
84
91
|
}
|
|
85
92
|
return state;
|
|
86
93
|
}catch(error){if(!report)throw error;notice='gemini_operation_failed';words('gemini-note',notice);el('gemini-note').title=error.message}
|
|
87
|
-
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}}))}
|
|
88
95
|
}
|
|
89
|
-
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)};
|
|
90
97
|
el('gemini-enabled').addEventListener('change',event=>void load(event.target.checked?'enable':'disable'));
|
|
91
98
|
el('gemini-model-form').addEventListener('submit',event=>{event.preventDefault();if(dirty())void load('models',{models:draft||selected(),...(defaultDraft!==undefined?{default_model:defaultDraft}:{})})});
|
|
92
99
|
el('gemini-cancel').addEventListener('click',()=>{draft=null;defaultDraft=undefined;notice=null;clear('gemini-note');render()});
|
package/src/dashboard/index.html
CHANGED
|
@@ -176,9 +176,9 @@
|
|
|
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"
|
|
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><th data-i18n="
|
|
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
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
184
|
<p id="gemini-default-note" class="hint" role="status" hidden></p>
|
|
@@ -190,7 +190,7 @@
|
|
|
190
190
|
<p class="hint" data-i18n="gemini_scope">Native Google models remain available. Copilot models and background requests use Copilot.</p>
|
|
191
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>
|
|
192
192
|
<p id="gemini-reopen" class="hint" data-i18n="gemini_reopen" hidden>Quit Gemini, then open it here to load CCDX models.</p>
|
|
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">
|
|
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>
|
|
194
194
|
</details>
|
|
195
195
|
<details class="panel dashboard-section"><summary data-i18n="gemini_activity">Connection activity</summary>
|
|
196
196
|
<p class="hint" data-i18n="gemini_activity_scope">Includes model requests and client discovery.</p>
|
|
@@ -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: ["
|
|
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: ["
|
|
53
|
-
gemini_pause_reopen: ["
|
|
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,8 +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", "默认"],
|
|
409
|
-
"gemini_use_app_default": ["Use app default", "
|
|
410
|
-
"gemini_default_unavailable": ["
|
|
415
|
+
"gemini_use_app_default": ["Use app default", "使用应用默认"],
|
|
416
|
+
"gemini_default_unavailable": ["Choose a default model in the app.", "请在应用内选择默认模型。"],
|
|
411
417
|
"cap_set_default": ["Set default", "设为默认"],
|
|
412
418
|
"cap_details": ["Details", "能力详情"],
|
|
413
419
|
"cap_app_access": ["App access", "应用接入"],
|
|
@@ -1021,7 +1027,18 @@
|
|
|
1021
1027
|
"attempt_timings": ["Send attempts", "发送次数"],
|
|
1022
1028
|
"body_queue_wait": ["Local queue history", "本机排队记录"],
|
|
1023
1029
|
"source_queue_wait": ["Source queue", "来源排队"],
|
|
1024
|
-
"
|
|
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}。"],
|
|
1025
1042
|
"body_queue_admitted": ["Admitted", "已放行"],
|
|
1026
1043
|
"body_queue_timed_out": ["Queue timed out", "排队超时"],
|
|
1027
1044
|
"body_queue_aborted": ["Wait cancelled", "等待已取消"],
|
|
@@ -1196,7 +1213,7 @@
|
|
|
1196
1213
|
"code": ["Error code", "错误代码"],
|
|
1197
1214
|
"message": ["Error details", "错误详情"],
|
|
1198
1215
|
"response_id": ["Response ID", "回答编号"],
|
|
1199
|
-
"upstream_request_id": ["Source request ID", "
|
|
1216
|
+
"upstream_request_id": ["Source request ID", "来源返回编号"],
|
|
1200
1217
|
"upstream_code": ["Source error code", "来源错误码"],
|
|
1201
1218
|
"request_id": ["CCDX request ID", "本机编号"],
|
|
1202
1219
|
"outcome_25a63": ["Result", "处理结果"],
|
package/src/dashboard/status.js
CHANGED
|
@@ -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 ===
|
|
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,
|
|
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
|
-
|
|
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 || "—"],
|
|
@@ -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 }) } : {}),
|
package/src/responses-bridge.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
}
|
package/src/source-transport.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
}
|
package/src/upstream-headers.mjs
CHANGED
|
@@ -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
|