codex-copilot-dx 1.4.5 → 1.4.7

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
@@ -258,7 +258,11 @@ For an identified conversation, hovering a point in the input-history chart show
258
258
 
259
259
  ## Shared source concurrency
260
260
 
261
- 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; unknown-length uploads retain their full reservation until fully read, then shrink to their actual held bytes. Recovery and internal summaries acquire fresh slots after the rejected response releases its slot.
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.
262
+
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.
264
+
265
+ 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.
262
266
 
263
267
  Automatic control distinguishes explicit concurrency rejection, request-rate feedback and quota exhaustion. Clear concurrency feedback lowers capacity without interrupting active streams; stable successful traffic with real waiting demand slowly increases it. Explicit account-wide rate/quota evidence pauses that account; model-scoped feedback leaves sibling models available after a short spacing interval. Unknown 429s use bounded backoff. Parameters, permissions and long thinking time do not train concurrency. There are no quota probes or automatic source/account/model switches. A first upstream limit rejection can still occur before its capacity is known.
264
268
 
@@ -808,7 +812,7 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
808
812
  | `CCDX_ALLOW_LAN` | unset | Set to `1` to permit a non-loopback host such as `0.0.0.0`; this exposes the Copilot-backed adapter beyond this machine |
809
813
  | `CCDX_MAX_BODY_BYTES` | `67108864` | Maximum compressed or raw request-body size |
810
814
  | `CCDX_MAX_DECODED_BODY_BYTES` | `134217728` | Maximum decoded request-body size after decompression |
811
- | `CCDX_MAX_INFLIGHT_BODY_BYTES` | `33554432` | Per-pool byte budget for raw bodies, decoded bodies, and materialized response history; a larger item runs exclusively in its pool |
815
+ | `CCDX_MAX_INFLIGHT_BODY_BYTES` | `33554432` | Per-pool byte budget for raw bodies, decoded bodies, and materialized response history; overrides the saved shared request-body setting. A larger item runs exclusively in its pool |
812
816
  | `CCDX_MAX_UPSTREAM_CHAT_RESPONSE_BYTES` | `67108864` | Maximum buffered successful Chat Completions response used by the internal Responses compatibility path |
813
817
  | `CCDX_MAX_UPSTREAM_RESPONSES_RESPONSE_BYTES` | `268435456` | Maximum buffered successful native Responses or compact response; streaming Responses use bounded backpressure |
814
818
  | `CCDX_MAX_QUEUED_REQUESTS` | `16` | Maximum body requests waiting for shared byte admission |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.4.5",
3
+ "version": "1.4.7",
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",
package/src/adapter.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { imageModelCatalog } from "./image-models.mjs";
2
2
  import http from "node:http";
3
- import { readUserSettings } from "./user-settings.mjs";
3
+ import { inflightBodyLimitPreference, readUserSettings } from "./user-settings.mjs";
4
4
  import { createNativeImagesHandler } from "./native-images.mjs";
5
5
  import { defaultCopilotClient } from "./copilot.mjs";
6
6
  import { buildCodexModelResponse } from "./codex-model-catalog.mjs";
@@ -177,7 +177,10 @@ export function createAdapterHandler(options = {}) {
177
177
  const streamHandshakeTimeoutMs = parsePositiveInteger(options.streamHandshakeTimeoutMs, ADAPTER_RUNTIME_CONFIG.streamHandshakeTimeoutMs);
178
178
  const streamIdleTimeoutMs = parsePositiveInteger(options.streamIdleTimeoutMs, ADAPTER_RUNTIME_CONFIG.streamIdleTimeoutMs);
179
179
  const requestBodyTimeoutMs = parsePositiveInteger(options.requestBodyTimeoutMs, ADAPTER_RUNTIME_CONFIG.requestBodyTimeoutMs);
180
- const acquireRequest = options.acquireRequest || createRequestAdmission();
180
+ const acquireRequest = options.acquireRequest || createRequestAdmission({
181
+ maxBytes: inflightBodyLimitPreference({ env: options.env, home: options.dashboardOptions?.home }).bytes,
182
+ maxSupplementalBytes: options.env ? loadRuntimeConfig(options.env).maxInflightBodyBytes : ADAPTER_RUNTIME_CONFIG.maxInflightBodyBytes,
183
+ });
181
184
  const requestMetrics = options.requestMetrics || createRequestMetrics();
182
185
  const streamPerformanceMetrics = options.streamPerformanceMetrics || createStreamPerformanceMetrics({ routeNames: ["responses", "responses_compact", "antigravity"] });
183
186
  const imagePressure = options.imagePressure || createResponsesImagePressureController();
@@ -567,6 +570,7 @@ export function createAdapterHandler(options = {}) {
567
570
  requestId,
568
571
  purpose,
569
572
  pathname,
573
+ route: routeName,
570
574
  showRequestId: options.showRequestId === true,
571
575
  includeHttpErrorDetails: options.includeHttpErrorDetails === true || process.env.CCDX_HTTP_ERROR_DETAILS === "1",
572
576
  streamPerformance,
@@ -73,7 +73,13 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
73
73
  const method=match[1];
74
74
  if(controlMethods.has(method))applicationEvidence?.notice(req,res,"antigravity","control");
75
75
  if(req.method==="POST"&&!/^application\/json(?:;|$)/i.test(req.headers["content-type"]||""))throw httpError("Antigravity requires JSON",415);
76
- phase="admission";release=await measureRequestStageAsync("admission",()=>acquireRequest(req,{signal:abort.signal}));
76
+ const length=req.headers["content-length"];
77
+ const bodylessControl=req.method==="GET"&&controlMethods.has(method)&&req.headers["transfer-encoding"]===undefined
78
+ &&(length===undefined||typeof length==="string"&&/^0+$/.test(length));
79
+ 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"}));
77
83
  phase="body";abort.setTimeout(requestBodyTimeoutMs,"request_body_timeout");
78
84
  body=req.method==="POST"?await measureRequestStageAsync("body",()=>readJsonBody(req,{admission:release,signal:abort.signal,parse:parseBody})):null;
79
85
  phase="preparation";
@@ -128,22 +134,27 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
128
134
  const response=value?.response||value,event=googleUsageEvent(value);if(event)captureUsage(event);
129
135
  const candidates=response?.candidates||[];
130
136
  if(candidates.some(candidate=>candidate.content?.parts?.some(part=>part.functionCall||!part.thought&&typeof part.text==="string"&&part.text)))markFirstOutput("delta");
131
- if(response?.error){outcome="failed";sourceResponseFailed(upstream)}
137
+ if(response?.error){outcome="failed";markResponseErrorOrigin("upstream_event");sourceResponseFailed(upstream)}
132
138
  else if(outcome!=="failed"&&candidates.some(candidate=>candidate.finishReason)){
133
139
  sourceResponseAccepted(upstream);
134
140
  outcome=candidates.every(candidate=>candidate.finishReason==="STOP")?"completed":"incomplete";
135
141
  }
136
142
  }}):null;
137
143
  res.writeHead(upstream.status,safeUpstreamResponseHeaders(upstream.headers));
144
+ let observedEof=false;
145
+ const finishObservation=()=>{if(observer?.finish().unavailable&&!usageEvent)markRequestObservation({usage_state:"unavailable"})};
138
146
  try{
139
147
  if(upstream.body){const reader=sourceResponseReader(upstream);try{while(true){
140
- let next;try{next=await reader.read()}catch(error){failSourceRead(reader);throw error}observeSourceRead(reader,next);if(next.done)break;
148
+ let next;try{next=await reader.read()}catch(error){failSourceRead(reader);throw error}
149
+ if(next.done){observedEof=true;finishObservation();observeSourceRead(reader,next);break}
150
+ observeSourceRead(reader,next);
141
151
  abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout");observer?.push(next.value);
142
152
  if(!await writeOrDrain(res,next.value,{signal:abort.signal}))throw httpError("Antigravity client disconnected",499);
143
153
  }}finally{await cancelSourceReader(reader).catch(()=>{});releaseSourceReader(reader)}}
144
- }finally{if(observer?.finish().unavailable&&!usageEvent)markRequestObservation({usage_state:"unavailable"})}
154
+ }finally{if(!observedEof)finishObservation()}
145
155
  if(generation&&!upstream.ok)outcome="failed";
146
- if(outcome)markResponseTerminal(outcome,upstream.ok?undefined:{origin:"upstream_http"});
156
+ if(outcome==="failed")counts.failed++;
157
+ if(outcome)markResponseTerminal(outcome,outcome==="failed"?{origin:upstream.ok?"upstream_event":"upstream_http"}:undefined);
147
158
  res.end();
148
159
  };
149
160
  if(!generation){
@@ -25,6 +25,7 @@ export function googleUsageEvent(value) {
25
25
  export function createGoogleResponseObserver({ streaming, onEvent, maxBytes = MAX_BYTES }) {
26
26
  const decoder = new TextDecoder("utf-8", { fatal: true });
27
27
  let parts = [], bytes = 0, data = [], frameBytes = 0, skipLF = false, skipFrame = false, unavailable = false;
28
+ let rawTail = null, rawBytes = 0;
28
29
  const parse = text => {
29
30
  if (!text || text === "[DONE]") return;
30
31
  try { const value = JSON.parse(text);for (const item of Array.isArray(value) ? value : [value]) onEvent(item); }
@@ -32,7 +33,12 @@ export function createGoogleResponseObserver({ streaming, onEvent, maxBytes = MA
32
33
  };
33
34
  const line = () => {
34
35
  const text = parts.join("");parts = [];bytes = 0;
35
- if (!text) {
36
+ if (rawTail !== null || !skipFrame && data.length === 0 && text.trimStart().startsWith("{")) {
37
+ rawTail ??= "";
38
+ rawBytes += Buffer.byteLength(text) + 1;
39
+ if (rawBytes > maxBytes) { rawTail = "";unavailable = true; }
40
+ else rawTail += text + "\n";
41
+ } else if (!text) {
36
42
  if (!skipFrame) parse(data.join("\n"));
37
43
  data = [];frameBytes = 0;skipFrame = false;
38
44
  } else if (!skipFrame && text.startsWith("data:")) {
@@ -76,10 +82,16 @@ export function createGoogleResponseObserver({ streaming, onEvent, maxBytes = MA
76
82
  finish() {
77
83
  try {
78
84
  consume(decoder.decode());
79
- if (streaming) { if (parts.length) line();if (!skipFrame && data.length) parse(data.join("\n")); }
80
- else if (!unavailable) parse(parts.join(""));
85
+ if (streaming) {
86
+ if (parts.length) line();
87
+ if (!skipFrame && data.length) parse(data.join("\n"));
88
+ if (!skipFrame && rawTail && rawBytes <= maxBytes) {
89
+ const value = JSON.parse(rawTail);
90
+ if (value?.error && typeof value.error === "object" && !Array.isArray(value.error)) onEvent(value);
91
+ }
92
+ } else if (!unavailable) parse(parts.join(""));
81
93
  } catch { unavailable = true; }
82
- parts = [];data = [];
94
+ parts = [];data = [];rawTail = null;
83
95
  return { unavailable };
84
96
  },
85
97
  };
@@ -8,19 +8,23 @@ export function createCarbonSearchHandler({ acquireRequest, privacy, resolveProv
8
8
  const abort = createRequestAbort(req, res);
9
9
  let release = () => {};
10
10
  try {
11
- release = await acquireRequest(req, { signal: abort.signal });
11
+ release = await acquireRequest(req, { signal: abort.signal, streamingBody: true });
12
12
  abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
13
- const body = await readJsonBody(req, { admission: release, signal: abort.signal });
14
- if (!body || typeof body !== "object" || Array.isArray(body)) throw httpError("Invalid search request", 400);
15
- const provider = resolveProvider?.(body, req);
16
- if (body.model !== "gemini-4-carbon" || provider && provider.id !== "github") {
17
- throw httpError("This search route is only available to GitHub Carbon", 400);
13
+ let upstream;
14
+ {
15
+ const body = await readJsonBody(req, { admission: release, signal: abort.signal });
16
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw httpError("Invalid search request", 400);
17
+ const provider = resolveProvider?.(body, req);
18
+ if (body.model !== "gemini-4-carbon" || provider && provider.id !== "github") {
19
+ throw httpError("This search route is only available to GitHub Carbon", 400);
20
+ }
21
+ if (!searchFn) throw httpError("Carbon search is unavailable", 503);
22
+ const search = privacy?.wrap(searchFn, { res, protocol: "search", client: "codex" }) || searchFn;
23
+ abort.setTimeout(upstreamTimeoutMs, "upstream_timeout");
24
+ const { input, ...searchBody } = body;
25
+ upstream = await search(searchBody, { signal: abort.signal, providerProfile: provider?.profileId?.() });
18
26
  }
19
- if (!searchFn) throw httpError("Carbon search is unavailable", 503);
20
- const search = privacy?.wrap(searchFn, { res, protocol: "search", client: "codex" }) || searchFn;
21
- abort.setTimeout(upstreamTimeoutMs, "upstream_timeout");
22
- const { input, ...searchBody } = body;
23
- const upstream = await search(searchBody, { signal: abort.signal, providerProfile: provider?.profileId?.() });
27
+ release();release = () => {};
24
28
  const text = await readBoundedResponseText(upstream, { maxBytes: upstream.ok ? MAX_UPSTREAM_CHAT_SUCCESS_BODY_BYTES : MAX_UPSTREAM_ERROR_BODY_BYTES,
25
29
  signal: abort.signal, label: "Carbon search" });
26
30
  if (!upstream.ok) { sendUpstreamError(res, upstream, text);return; }
@@ -247,7 +247,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
247
247
  context.streamPerformance = tracker;context.route = countTokens ? "messages_count_tokens" : "messages";
248
248
  await runWithRequestContext(context, async () => {
249
249
  try {
250
- release = await acquireRequest(req, { signal: abort.signal });
250
+ release = await acquireRequest(req, { signal: abort.signal, streamingBody: true });
251
251
  abort.setTimeout(config.requestBodyTimeoutMs, "request_body_timeout");
252
252
  let body = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: config.maxBodyBytes, maxDecodedBodyBytes: decodedLimit });
253
253
  abort.setTimeout(config.upstreamTimeoutMs, "messages_prepare_timeout");
@@ -2,7 +2,7 @@ import os from "node:os";
2
2
  import { MIB } from "./cache-limits.mjs";
3
3
  import { readAdapterStatus } from "./cli-status.mjs";
4
4
  import { loadRuntimeConfig } from "./runtime-config.mjs";
5
- import { decodedBodyLimitPreference, writeDecodedBodyLimitMib } from "./user-settings.mjs";
5
+ import { decodedBodyLimitPreference, writeDecodedBodyLimitMib, inflightBodyLimitPreference } from "./user-settings.mjs";
6
6
 
7
7
  function mib(bytes) {
8
8
  const value = Number(bytes);
@@ -37,6 +37,8 @@ export async function runLimitsCommand({
37
37
  } catch {
38
38
  runtime = null;
39
39
  }
40
+ const inflight = inflightBodyLimitPreference({ env, home });
41
+ const activeInflight = runtime?.data?.admission?.maxBytes;
40
42
  const activeDecoded = Number(runtime?.data?.limits?.max_decoded_body_bytes);
41
43
  const activeRaw = Number(runtime?.data?.limits?.max_body_bytes);
42
44
  const lines = [
@@ -45,10 +47,13 @@ export async function runLimitsCommand({
45
47
  runtime && Number.isFinite(activeDecoded) && activeDecoded > 0
46
48
  ? `Running decoded request body: ${mib(activeDecoded)}`
47
49
  : "Running decoded request body: unavailable",
50
+ `Configured shared request-body budget: ${mib(inflight.bytes)} (${inflight.source})`,
51
+ Number.isFinite(activeInflight) && activeInflight > 0 ? `Running shared request-body budget: ${mib(activeInflight)}` : "Running shared request-body budget: unavailable",
48
52
  `Raw request body: ${mib(runtime && Number.isFinite(activeRaw) && activeRaw > 0 ? activeRaw : loadRuntimeConfig(env).maxBodyBytes)}${runtime ? " (running)" : " (configured)"}`,
49
53
  ];
50
54
  if (!runtime) lines.push("Running adapter status unavailable; restart ccdx to apply and verify this limit.");
51
55
  else if (activeDecoded !== preference.bytes) lines.push("Restart ccdx to apply the configured decoded-body limit.");
56
+ if (Number.isFinite(activeInflight) && activeInflight !== inflight.bytes) lines.push("Restart ccdx to apply the configured shared request-body budget.");
52
57
  if (action === "set") lines.push("Existing conversations and caches were not modified.");
53
58
  output.write(`${lines.join("\n")}\n`);
54
59
  return { preference, runtime };
@@ -162,6 +162,11 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
162
162
  status("info", `Conversation buffer: ${mebibytes(history.bytes)} / ${mebibytes(limits.response_history_max_bytes)}, ${count(history.entries)} entries, ${count(history.evicted)} evicted ID markers`),
163
163
  status("info", `Image cache: ${count(images.cache_entries)} entries, ${cacheHitRate(images)} hits, ${mebibytes(images.cache_bytes)} / ${mebibytes(images.cache_max_bytes)}`),
164
164
  ];
165
+ const longest = admission.longestWait;
166
+ if (longest) {
167
+ const reason = longest.reason === "exclusive_waiter" ? "exclusive request ahead" : "request-body memory budget";
168
+ lines.push(status("info", `Longest local queue: ${latency(longest.wait_ms)} · ${longest.route} · ${reason} · needs ${mebibytes(longest.requested_bytes)}, used ${mebibytes(longest.active_bytes)}/${mebibytes(longest.limit_bytes)}${longest.request_id ? ` · ${longest.request_id}` : ""}`));
169
+ }
165
170
  const sourceRoutes = { ...data.stream_performance?.by_route, ...(data.providers?.claude || data.providers?.m365?.claude)?.requests?.performance?.by_route };
166
171
  for (const [route, metrics] of Object.entries(sourceRoutes)) for (const [source, stats] of Object.entries(metrics.by_provider || {})) {
167
172
  const totals = stats.terminal_outcomes.totals;
@@ -217,9 +217,9 @@
217
217
  settingsPending = true;
218
218
  applications?.render();
219
219
  syncAccountControls();
220
- const controls = [...document.querySelectorAll("[role=switch], #save-history, #clean-history, #fix-prediction, #apply-source, #save-review, #source-provider, #source-model, #source-review, #source-review-effort, #terminal-color-theme, #m365-enabled, #prediction-continue, #prediction-open, #prediction-setup, #prediction-remove, #image-models input, #image-check, #image-repair, #image-open, #decoded-limit, #decoded-limit-save, #decoded-limit-default, #install-update")];
220
+ const controls = [...document.querySelectorAll("[role=switch], #save-history, #clean-history, #fix-prediction, #apply-source, #save-review, #source-provider, #source-model, #source-review, #source-review-effort, #terminal-color-theme, #m365-enabled, #prediction-continue, #prediction-open, #prediction-setup, #prediction-remove, #image-models input, #image-check, #image-repair, #image-open, #decoded-limit, #decoded-limit-save, #decoded-limit-default, #inflight-body-limit, #inflight-body-limit-save, #inflight-body-limit-default, #install-update")];
221
221
  controls.forEach(input => { input.disabled = true; });
222
- const note = el(body.action === "application" ? "application-state" : body.key === "codex_auto_launch" ? "codex-auto-launch-note" : body.action === "codex_app" ? body.intent === "prediction" ? "prediction-open-note" : "image-action-note" : body.action === "prediction" ? body.operation === "open" ? "prediction-open-note" : "prediction-action-note" : body.action === "image" ? "effect-image_enabled" : body.action === "update" ? "manual-update-note" : body.action === "decoded_limit" ? "decoded-limit-note" : body.action === "nightly_update" ? "nightly-state" : body.key ? `effect-${body.key}` : body.action === "color_theme" ? "terminal-color-note"
222
+ const note = el(body.action === "application" ? "application-state" : body.key === "codex_auto_launch" ? "codex-auto-launch-note" : body.action === "codex_app" ? body.intent === "prediction" ? "prediction-open-note" : "image-action-note" : body.action === "prediction" ? body.operation === "open" ? "prediction-open-note" : "prediction-action-note" : body.action === "image" ? "effect-image_enabled" : body.action === "update" ? "manual-update-note" : body.action === "decoded_limit" ? "decoded-limit-note" : body.action === "inflight_body_limit" ? "inflight-body-limit-note" : body.action === "nightly_update" ? "nightly-state" : body.key ? `effect-${body.key}` : body.action === "color_theme" ? "terminal-color-note"
223
223
  : body.action.startsWith("history_") ? "effect-history" : body.action === "prediction_fix" ? "prediction-note"
224
224
  : body.operation === "switch" ? "source-control-note" : body.operation === "auto-review" ? "review-control-note"
225
225
  : body.operation === "account" ? "m365-account-note" : "m365-control-note");
@@ -1,6 +1,6 @@
1
1
  (() => {
2
2
  function create({ element: el, change, localize }) {
3
- let saved = null, limitDirty = false, imageSignature = "", imageApp = { status: "unknown" }, appInspectionStarted = false;
3
+ let saved = null, limitDirty = false, inflightDirty = false, imageSignature = "", imageApp = { status: "unknown" }, appInspectionStarted = false;
4
4
  function renderImageApp() {
5
5
  const connected = imageApp.status === "running" && imageApp.host === "connected";
6
6
  const restart = imageApp.status === "running" && (imageApp.needs_restart === true || saved?.features?.prediction?.display_pending === true);
@@ -67,6 +67,22 @@
67
67
  };
68
68
  el("decoded-limit-save").addEventListener("click", () => void saveLimit(Number(el("decoded-limit").value)));
69
69
  el("decoded-limit-default").addEventListener("click", () => void saveLimit(null));
70
+ const inflightField = el("inflight-body-limit");
71
+ inflightField.addEventListener("input", () => { inflightDirty = true; });
72
+ const saveInflight = async useDefault => {
73
+ if (inflightField.disabled) return;
74
+ if (!useDefault && !inflightField.checkValidity()) {
75
+ localize(el("inflight-body-limit-note"), "ccdx_inflight_limit_invalid");
76
+ return;
77
+ }
78
+ const data = await change({ action: "inflight_body_limit", mib: useDefault ? null : inflightField.valueAsNumber }, el(useDefault ? "inflight-body-limit-default" : "inflight-body-limit-save"));
79
+ if (data?.inflight_body) { inflightDirty = false;inflightField.value = data.inflight_body.bytes / 1048576;render(data); }
80
+ };
81
+ el("inflight-body-limit-save").addEventListener("click", () => void saveInflight(false));
82
+ el("inflight-body-limit-default").addEventListener("click", () => void saveInflight(true));
83
+ inflightField.addEventListener("keydown", event => {
84
+ if (event.key === "Enter") { event.preventDefault();void saveInflight(false); }
85
+ });
70
86
  el("install-update").addEventListener("click", () => {
71
87
  if (window.confirm(globalThis.ccdxLanguage.format("update_install_confirm"))) void change({ action: "update", confirmed: true }, el("install-update"));
72
88
  });
@@ -111,6 +127,10 @@
111
127
  if (!limitDirty && document.activeElement !== el("decoded-limit")) el("decoded-limit").value = limit?.bytes / 1048576 || 128;
112
128
  el("decoded-limit").disabled = el("decoded-limit-save").disabled = el("decoded-limit-default").disabled = !limit || limit.source === "environment";
113
129
  localize(el("decoded-limit-note"), limit?.source === "environment" ? "controlled_by_environment" : "next_ccdx_start");
130
+ const inflight = data.inflight_body;
131
+ if (inflight && (!inflightDirty && document.activeElement !== inflightField || inflight.source === "environment")) inflightField.value = inflight.bytes / 1048576;
132
+ inflightField.disabled = el("inflight-body-limit-save").disabled = el("inflight-body-limit-default").disabled = !inflight || inflight.source === "environment";
133
+ localize(el("inflight-body-limit-note"), !inflight ? "feature_unavailable" : inflight.source === "environment" ? "controlled_by_environment" : "inflight_body_limit_next_start");
114
134
  el("install-update").disabled = !data.manual_update?.available;
115
135
  const update = data.nightly_update;
116
136
  if (notes) localize(el("manual-update-note"), !data.manual_update?.available ? "update_external_launch" : update?.manual ? `manual_update_${update.phase}` : "update_idle_switch");
@@ -506,7 +506,7 @@
506
506
  <div class="section-actions"><button id="privacy-cancel" type="button" hidden data-i18n="cancel">Cancel</button><button id="privacy-retry" type="button" hidden data-i18n="view_retry">Retry</button><button id="privacy-remove" type="button" hidden data-i18n="privacy_remove">Delete model</button><p id="privacy-error" class="hint" role="alert"></p></div>
507
507
  </section>
508
508
  <dialog id="privacy-dialog" class="preferences-dialog" aria-labelledby="privacy-dialog-title"><h2 id="privacy-dialog-title" data-i18n="privacy_enable">Local masking</h2><p data-i18n="privacy_download">Downloads about 39 MB plus the local component. Checks may add delay or mistake ordinary text.</p><p data-i18n="privacy_fail_closed">If a check cannot finish, the request is not sent.</p><div class="section-actions"><button id="privacy-dialog-cancel" type="button" data-i18n="cancel">Cancel</button><button id="privacy-dialog-confirm" type="button" data-i18n="privacy_confirm">Download &amp; enable</button></div></dialog>
509
- <details class="panel dashboard-section" id="request-limits"><summary data-i18n="advanced_limits">Advanced: request limits</summary><div class="section-actions"><label><span data-i18n="decoded_limit">Decoded request limit (MiB)</span><input id="decoded-limit" type="number" min="128" max="512" step="1"></label><button id="decoded-limit-save" type="button" data-i18n="api_save">Save</button><button id="decoded-limit-default" type="button" data-i18n="limit_default">Use default</button></div><p id="decoded-limit-note" class="hint" role="status"></p></details>
509
+ <details class="panel dashboard-section" id="request-limits"><summary data-i18n="advanced_limits">Advanced: request limits</summary><div class="section-actions"><label><span data-i18n="decoded_limit">Decoded request limit (MiB)</span><input id="decoded-limit" type="number" min="128" max="512" step="1"></label><button id="decoded-limit-save" type="button" data-i18n="api_save">Save</button><button id="decoded-limit-default" type="button" data-i18n="limit_default">Use default</button></div><p id="decoded-limit-note" class="hint" role="status"></p><div class="section-actions"><label><span data-i18n="inflight_body_limit">Shared request-body limit (MiB)</span> <input id="inflight-body-limit" type="number" min="32" max="128" step="1" required aria-describedby="inflight-body-limit-note" disabled></label><button id="inflight-body-limit-save" type="button" data-i18n="api_save" disabled>Save</button><button id="inflight-body-limit-default" type="button" data-i18n="limit_default" disabled>Use default</button></div><p id="inflight-body-limit-note" class="hint" role="status"></p></details>
510
510
  <section class="panel dashboard-section" id="settings-preferences" aria-labelledby="preferences-heading">
511
511
  <h2 id="preferences-heading" data-i18n="preferences_heading">SAVE &amp; RESTORE</h2>
512
512
  <div class="preferences-row"><div><label for="preferences-auto" data-i18n="preferences_auto">Save changes automatically</label><p class="hint" data-i18n="preferences_auto_hint">Valid changes on this page save automatically.</p></div><input id="preferences-auto" type="checkbox" role="switch" disabled checked></div>
@@ -120,6 +120,9 @@
120
120
  compatibility_scope: ["Tests Codex Responses, streaming and compaction. Uses quota.", "测试 Codex Responses、流式响应与压缩,会消耗用量。"],
121
121
  advanced_limits: ["Advanced: request limits", "高级:请求限制"],
122
122
  decoded_limit: ["Decoded request limit (MiB)", "解码后请求上限(MiB)"],
123
+ inflight_body_limit: ["Shared request-body limit (MiB)", "共享请求体内存额度(MiB)"],
124
+ inflight_body_limit_next_start: ["Multiple requests share this budget. Changes apply next time CCDX starts.", "多条请求的正文共用此额度。下次启动 CCDX 时生效。"],
125
+ ccdx_inflight_limit_invalid: ["Enter a whole number from 32 to 128 MiB.", "请输入 32 至 128 MiB 之间的整数。"],
123
126
  prediction_remove_confirm: ["Remove the CCDX prediction trust and route? Quit Codex to finish cleanup.", "移除 CCDX 预测信任与路由?退出 Codex 后才能完成清理。"],
124
127
  update_install_confirm: ["Install the latest stable release and switch CCDX when idle? Active work postpones the switch.", "安装最新稳定版并在空闲时切换 CCDX?有执行中的工作时会推迟切换。"],
125
128
  feature_unavailable: ["Restart the updated CCDX to use these controls.", "重启更新后的 CCDX 以使用这些控制。"],
@@ -1014,6 +1017,18 @@
1014
1017
  "requested_model": ["Requested model", "指定模型"],
1015
1018
  "request_kind": ["Request purpose", "请求用途"],
1016
1019
  "attempt_timings": ["Send attempts", "发送次数"],
1020
+ "body_queue_wait": ["Local queue history", "本机排队记录"],
1021
+ "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}。"],
1023
+ "body_queue_admitted": ["Admitted", "已放行"],
1024
+ "body_queue_timed_out": ["Queue timed out", "排队超时"],
1025
+ "body_queue_aborted": ["Wait cancelled", "等待已取消"],
1026
+ "body_queue_result_unknown": ["Result not recorded", "未记录排队结果"],
1027
+ "body_queue_exclusive": ["An earlier request needed exclusive access", "前方请求需独占额度"],
1028
+ "body_queue_upload_in_progress": ["Another unknown-length upload was still being read", "前一条未知长度的上传还没读完"],
1029
+ "body_queue_upload_growth": ["An upload already in progress was waiting for more memory", "正在读入的上传需要更多内存额度"],
1030
+ "body_queue_unknown_length": ["Unknown body length required a full reservation", "请求长度未知,需预留全部额度"],
1031
+ "body_queue_budget": ["Remaining budget could not cover the reservation", "剩余额度不足以预留本请求"],
1017
1032
  "gateway_timing_output_speed_is_estimated": ["Estimated by CCDX. Not internal model time or total throughput.", "由 CCDX 估算。\n不代表模型内部耗时或总吞吐。"],
1018
1033
  "value_samples_samples": ["{value} / {samples} samples", "{value} / {samples}次样本"],
1019
1034
  "ccdx_local_dashboard": ["CCDX · Dashboard", "CCDX · 运行面板"],
@@ -400,15 +400,28 @@
400
400
  details.className = "request-details";fields.className = "failure-detail";
401
401
  if (Number.isSafeInteger(context.privacy_count)) globalThis.ccdxLanguage.set(summary, "privacy_result", { count: context.privacy_count, ms: context.privacy_ms || 0 });
402
402
  else localize(summary, "request_metadata");details.append(summary, fields);
403
+ const queue = context.body_queue;
404
+ const queueResult = queue?.outcome === "admitted" ? "body_queue_admitted" : queue?.outcome === "timed_out" ? "body_queue_timed_out"
405
+ : queue?.outcome === "aborted" ? "body_queue_aborted" : "body_queue_result_unknown";
406
+ const queueReason = queue?.reason === "upload_in_progress" ? "body_queue_upload_in_progress" : queue?.reason === "upload_growth" ? "body_queue_upload_growth"
407
+ : queue?.reason === "exclusive_waiter" ? "body_queue_exclusive"
408
+ : queue?.length_known === false && queue.requested_bytes === queue.limit_bytes ? "body_queue_unknown_length" : "body_queue_budget";
403
409
  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],
404
410
  ["time", Number.isFinite(at) ? time(at, { date: true }) : "—"],
411
+ ...(Number.isSafeInteger(queue?.wait_ms) ? [["body_queue_wait", phrase("body_queue_detail", {
412
+ ms: number(queue.wait_ms), result: phrase(queueResult), reason: phrase(queueReason),
413
+ reserved: mib(queue.requested_bytes), occupied: mib(queue.active_bytes), limit: mib(queue.limit_bytes),
414
+ })]] : []),
415
+ ...(Number.isSafeInteger(context.source_queue_ms) ? [["source_queue_wait", `${number(context.source_queue_ms)} ms`]] : []),
405
416
  ["wire_mib", finite(context.payload_bytes) ? `${(Number(context.payload_bytes) / 1048576).toFixed(2)} MiB` : "—"],
406
417
  ["images", number(context.images)], ["model_window", number(context.context_window_tokens)], ["input_window", ratio],
407
418
  ["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 || "—"],
408
419
  ...(context.requested_model && context.requested_model !== request.model ? [["requested_model", context.requested_model]] : []),
409
420
  ...(["reported", "partial", "missing", "unavailable"].includes(context.usage_state) ? [["request_usage_state", globalThis.ccdxLanguage?.format("request_usage_" + context.usage_state) || context.usage_state]] : []),
410
421
  ...(context.client_tool_errors_received > 0 ? [["client_tool_errors_received", number(context.client_tool_errors_received)]] : [])]) {
411
- const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);detail.textContent = value;fields.append(term, detail);
422
+ const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);
423
+ if (value?.key) localize(detail, value.key, value.values);else detail.textContent = value;
424
+ fields.append(term, detail);
412
425
  }
413
426
  row.children[5].append(details);body.append(row);
414
427
  }
@@ -37,7 +37,7 @@ function payloadTooLarge(kind, maxBytes) {
37
37
 
38
38
  function consumeRequestChunks(req, { signal, onChunk }) {
39
39
  return new Promise((resolve, reject) => {
40
- let settled = false;
40
+ let settled = false, waiting = false, ended = false;
41
41
  const cleanup = () => {
42
42
  req.off("data", handleData);
43
43
  req.off("end", handleEnd);
@@ -58,12 +58,21 @@ function consumeRequestChunks(req, { signal, onChunk }) {
58
58
  };
59
59
  const handleData = (chunk) => {
60
60
  try {
61
- onChunk(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
61
+ const pending = onChunk(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
62
+ if (pending) {
63
+ waiting = true;
64
+ req.pause();
65
+ pending.then(() => {
66
+ waiting = false;
67
+ if (settled) return;
68
+ if (ended) finish();else req.resume();
69
+ }, stopReading);
70
+ }
62
71
  } catch (error) {
63
72
  stopReading(error);
64
73
  }
65
74
  };
66
- const handleEnd = () => finish();
75
+ const handleEnd = () => { ended = true;if (!waiting) finish(); };
67
76
  const handleError = (error) => finish(error);
68
77
  const handleAborted = () => finish(admissionAbortError(signal));
69
78
  const handleSignalAbort = () => stopReading(admissionAbortError(signal));
@@ -80,7 +89,7 @@ function consumeRequestChunks(req, { signal, onChunk }) {
80
89
  });
81
90
  }
82
91
 
83
- async function readRequestBuffer(req, maxBytes, signal) {
92
+ async function readRequestBuffer(req, maxBytes, signal, growUpload) {
84
93
  const contentLength = requestContentLength(req);
85
94
  if (Number.isFinite(contentLength) && contentLength > maxBytes) {
86
95
  throw payloadTooLarge("Raw", maxBytes);
@@ -93,13 +102,15 @@ async function readRequestBuffer(req, maxBytes, signal) {
93
102
  onChunk(buffer) {
94
103
  total += buffer.length;
95
104
  if (total > maxBytes) throw payloadTooLarge("Raw", maxBytes);
105
+ const pending = growUpload?.(total, signal);
106
+ if (pending) return pending.then(() => { if (!signal?.aborted) chunks.push(buffer); });
96
107
  chunks.push(buffer);
97
108
  },
98
109
  });
99
110
  return Buffer.concat(chunks);
100
111
  }
101
112
 
102
- async function readIdentityText(req, maxBodyBytes, maxDecodedBodyBytes, signal, onBytes) {
113
+ async function readIdentityText(req, maxBodyBytes, maxDecodedBodyBytes, signal, admission) {
103
114
  const contentLength = requestContentLength(req);
104
115
  if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) {
105
116
  throw payloadTooLarge("Raw", maxBodyBytes);
@@ -125,6 +136,8 @@ async function readIdentityText(req, maxBodyBytes, maxDecodedBodyBytes, signal,
125
136
  total += buffer.length;
126
137
  if (total > maxBodyBytes) throw payloadTooLarge("Raw", maxBodyBytes);
127
138
  if (total > maxDecodedBodyBytes) throw payloadTooLarge("Decoded", maxDecodedBodyBytes);
139
+ const pending = admission?.growUpload?.(total, signal);
140
+ if (pending) return pending.then(() => { if (!signal?.aborted) text += decoder.decode(buffer, { stream: true }); });
128
141
  if (preallocatedLength) {
129
142
  allocated ||= Buffer.allocUnsafe(preallocatedLength);
130
143
  if (!overflow && total <= allocated.length) {
@@ -138,7 +151,7 @@ async function readIdentityText(req, maxBodyBytes, maxDecodedBodyBytes, signal,
138
151
  }
139
152
  },
140
153
  });
141
- onBytes?.(total);
154
+ admission?.resize?.(total);
142
155
  if (preallocatedLength) {
143
156
  if (!allocated) return "";
144
157
  return new TextDecoder().decode(overflow ? Buffer.concat(overflow, total) : allocated.subarray(0, total));
@@ -197,11 +210,11 @@ export async function readJsonBody(req, {
197
210
  parse = parseRequestJson,
198
211
  } = {}) {
199
212
  if (signal?.aborted) throw admissionAbortError(signal);
200
- const encodings = contentEncodings(req.headers?.["content-encoding"]);
201
- if (encodings.every((encoding) => encoding === "identity")) {
202
- return parse(await readIdentityText(req, maxBodyBytes, maxDecodedBodyBytes, signal, bytes => admission?.resize?.(bytes)));
213
+ const encoding = req.headers?.["content-encoding"];
214
+ if (!encoding || encoding === "identity" || contentEncodings(encoding).every(value => value === "identity")) {
215
+ return parse(await readIdentityText(req, maxBodyBytes, maxDecodedBodyBytes, signal, admission));
203
216
  }
204
- const buffer = await readRequestBuffer(req, maxBodyBytes, signal);
217
+ const buffer = await readRequestBuffer(req, maxBodyBytes, signal, admission?.growUpload);
205
218
  admission?.resize?.(buffer.length);
206
219
  let releaseDecompression = () => {};
207
220
  let decodedReservation;
@@ -17,9 +17,19 @@ export function createLocalPrivacy(options = {}) {
17
17
  const detection = createPrivacyDetection(model, options);
18
18
  let generation = 0, pending = null, disposed = false, lastResponse = null;
19
19
  let keyLoaded = false, actionError = null, lastCheck = null;
20
+ const settingsOptions = { ...options, strict: true }, absentPolicy = { enabled: false, personal: false };
21
+ let cachedPolicy;
20
22
  const settings = () => {
21
- const saved = readUserSettings({ ...options, strict: true });
22
- return { enabled: saved.privacy_enabled === true, personal: saved.privacy_personal === true };
23
+ const file = userSettingsPath(settingsOptions), stat = fs.statSync(file, { bigint: true, throwIfNoEntry: false });
24
+ if (!stat) { cachedPolicy = undefined;return absentPolicy; }
25
+ const previous = cachedPolicy?.stat;
26
+ // Check on every decision. No TTL: in-place edits, replacements and
27
+ // permission changes invalidate the last strictly validated policy.
28
+ if (previous && cachedPolicy.file === file && stat.ino !== 0n && previous.ino === stat.ino && previous.dev === stat.dev
29
+ && previous.mtimeNs === stat.mtimeNs && previous.ctimeNs === stat.ctimeNs && previous.size === stat.size && previous.mode === stat.mode) return cachedPolicy.policy;
30
+ const saved = readUserSettings(settingsOptions);
31
+ const policy = { enabled: saved.privacy_enabled === true, personal: saved.privacy_personal === true };
32
+ cachedPolicy = { file, stat, policy };return policy;
23
33
  };
24
34
  const revision = saved => createHash("sha256").update(JSON.stringify(saved)).digest("hex");
25
35
  const snapshot = () => { const saved = settings(), detector = model.snapshot();return { ...detector, ...saved,
@@ -74,7 +74,7 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
74
74
  if (processing >= 2) { metrics.busy++;throw httpError("Two image requests are already active", 503); }
75
75
  active++;processing++;admitted = true;processingSlot = true;
76
76
  abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
77
- release = await acquireRequest(req, { signal: abort.signal });
77
+ release = await acquireRequest(req, { signal: abort.signal, streamingBody: true });
78
78
  const parsed = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: BODY_MAX_BYTES, maxDecodedBodyBytes: BODY_MAX_BYTES });
79
79
  const available = models();
80
80
  const image = parsed?.model === "gpt-image-2" ? imageModelSelection(available, selection()).selected_model : parsed?.model;
@@ -1,11 +1,14 @@
1
1
  import { loadRuntimeConfig, parsePositiveInteger } from "./runtime-config.mjs";
2
2
  import { httpError } from "./http-errors.mjs";
3
+ import { currentRequestContext } from "./request-context.mjs";
3
4
 
4
5
  const HTTP_RUNTIME_CONFIG = loadRuntimeConfig();
5
6
  const MAX_INFLIGHT_BODY_BYTES = HTTP_RUNTIME_CONFIG.maxInflightBodyBytes;
6
7
  const MAX_QUEUED_REQUESTS = HTTP_RUNTIME_CONFIG.maxQueuedRequests;
7
8
  const REQUEST_QUEUE_TIMEOUT_MS = HTTP_RUNTIME_CONFIG.requestQueueTimeoutMs;
8
9
  const COMPRESSED_BODY_WEIGHT_MULTIPLIER = 4;
10
+ const ADMISSION_ROUTES = new Set(["responses", "responses_compact", "messages", "messages_count_tokens", "search", "images", "antigravity", "antigravity_control"]);
11
+ const RECENT_WAITS = 16;
9
12
 
10
13
  export function contentEncodings(contentEncoding) {
11
14
  return String(contentEncoding || "identity")
@@ -18,11 +21,10 @@ export function requestContentLength(req) {
18
21
  return Number.parseInt(req.headers?.["content-length"] || "", 10);
19
22
  }
20
23
 
21
- function requestAdmissionWeight(req, maxBytes) {
22
- const encodings = contentEncodings(req.headers?.["content-encoding"]);
23
- const contentLength = requestContentLength(req);
24
+ function requestAdmissionWeight(req, maxBytes, contentLength) {
24
25
  if (!Number.isFinite(contentLength) || contentLength < 0) return maxBytes;
25
- const compressed = encodings.some((encoding) => encoding !== "identity");
26
+ const encoding = req.headers?.["content-encoding"];
27
+ const compressed = encoding && encoding !== "identity" && contentEncodings(encoding).some(value => value !== "identity");
26
28
  const weightedLength = compressed ? contentLength * COMPRESSED_BODY_WEIGHT_MULTIPLIER : contentLength;
27
29
  return Math.max(1, Math.min(weightedLength, maxBytes));
28
30
  }
@@ -151,10 +153,12 @@ function createSupplementalAdmission({ maxWeight, maxQueued, waitTimeoutMs, labe
151
153
 
152
154
  export function createRequestAdmission({
153
155
  maxBytes = MAX_INFLIGHT_BODY_BYTES,
156
+ maxSupplementalBytes = maxBytes,
154
157
  maxQueued = MAX_QUEUED_REQUESTS,
155
158
  waitTimeoutMs = REQUEST_QUEUE_TIMEOUT_MS,
156
159
  } = {}) {
157
160
  const byteLimit = parsePositiveInteger(maxBytes, MAX_INFLIGHT_BODY_BYTES);
161
+ const supplementalByteLimit = parsePositiveInteger(maxSupplementalBytes, byteLimit);
158
162
  const queueLimit = parsePositiveInteger(maxQueued, MAX_QUEUED_REQUESTS);
159
163
  const timeoutMs = parsePositiveInteger(waitTimeoutMs, REQUEST_QUEUE_TIMEOUT_MS);
160
164
  const acquireDecompression = createSupplementalAdmission({
@@ -164,14 +168,14 @@ export function createRequestAdmission({
164
168
  label: "Request decompression",
165
169
  });
166
170
  const acquireDecodedBody = createSupplementalAdmission({
167
- maxWeight: byteLimit,
171
+ maxWeight: supplementalByteLimit,
168
172
  maxQueued: queueLimit,
169
173
  waitTimeoutMs: timeoutMs,
170
174
  label: "Decoded request body",
171
175
  blockBehindExclusive: true,
172
176
  });
173
177
  const acquireResponseHistory = createSupplementalAdmission({
174
- maxWeight: byteLimit,
178
+ maxWeight: supplementalByteLimit,
175
179
  maxQueued: queueLimit,
176
180
  waitTimeoutMs: timeoutMs,
177
181
  label: "Response history",
@@ -179,6 +183,19 @@ export function createRequestAdmission({
179
183
  const queue = [];
180
184
  let activeBytes = 0;
181
185
  let activeRequests = 0;
186
+ // Only one upload per pool can retain partial data and later ask for more.
187
+ // A blocked growth request goes before new admissions so it can make progress.
188
+ let progressiveReader = false;
189
+ let growth = null;
190
+ const recentWaits = [];
191
+ let longestWait = null;
192
+ function recordWait(entry, outcome, waitMs) {
193
+ const record = Object.freeze({ ...entry.evidence, outcome, wait_ms: waitMs });
194
+ if (outcome === "admitted" && (!longestWait || waitMs > longestWait.wait_ms)) longestWait = record;
195
+ if (recentWaits.length === RECENT_WAITS) recentWaits.shift();
196
+ recentWaits.push(record);
197
+ entry.tracker?.observeContext?.({ body_queue: record });
198
+ }
182
199
  const counters = {
183
200
  total: 0,
184
201
  activated: 0,
@@ -195,30 +212,50 @@ export function createRequestAdmission({
195
212
  if (index >= 0) queue.splice(index, 1);
196
213
  };
197
214
 
198
- const activate = (entry) => {
199
- entry.cleanup();
200
- activeBytes += entry.weight;
215
+ const activate = (weight, progressive) => {
216
+ activeBytes += weight;
217
+ if (progressive) progressiveReader = true;
218
+ let reading = progressive;
201
219
  activeRequests += 1;
202
220
  counters.activated += 1;
203
- const waitMs = Math.max(0, Date.now() - entry.startedAt);
204
- counters.waitMsTotal += waitMs;
205
- counters.waitMsMax = Math.max(counters.waitMsMax, waitMs);
206
221
  let released = false;
207
- const supplementalReleases = new Set();
222
+ let supplementalReleases;
208
223
  const release = () => {
209
224
  if (released) return;
210
225
  released = true;
211
- for (const releaseSupplemental of supplementalReleases) releaseSupplemental();
212
- supplementalReleases.clear();
213
- activeBytes = Math.max(0, activeBytes - entry.weight);
226
+ if (reading) {
227
+ growth?.cancel();
228
+ reading = progressiveReader = false;
229
+ }
230
+ if (supplementalReleases) {
231
+ for (const releaseSupplemental of supplementalReleases) releaseSupplemental();
232
+ supplementalReleases.clear();
233
+ }
234
+ activeBytes = Math.max(0, activeBytes - weight);
214
235
  activeRequests = Math.max(0, activeRequests - 1);
215
236
  drain();
216
237
  };
217
238
  release.resize = bytes => {
218
239
  if (released || !Number.isSafeInteger(bytes) || bytes < 0) return;
219
- const next = Math.max(1, Math.min(entry.weight, bytes));
220
- if (next === entry.weight) return;
221
- activeBytes -= entry.weight - next;entry.weight = next;drain();
240
+ const next = Math.max(1, Math.min(weight, bytes));
241
+ if (!reading && next === weight) return;
242
+ if (reading) reading = progressiveReader = false;
243
+ activeBytes -= weight - next;weight = next;drain();
244
+ };
245
+ if (progressive) release.growUpload = (bytes, signal) => {
246
+ if (!reading || signal?.aborted) throw admissionAbortError(signal);
247
+ // Preserve the existing exclusive handling for bodies larger than the pool.
248
+ // The independent per-request raw and decoded limits still apply.
249
+ const next = Math.min(byteLimit, bytes), extra = next - weight;
250
+ if (extra <= 0) return;
251
+ if (activeBytes + extra <= byteLimit) { weight = next;activeBytes += extra;return; }
252
+ return new Promise((resolve, reject) => {
253
+ const clear = () => { growth = null;signal?.removeEventListener("abort", cancel); };
254
+ const cancel = () => { clear();reject(admissionAbortError(signal)); };
255
+ growth = { extra, cancel, grant() { clear();weight = next;activeBytes += extra;resolve(); } };
256
+ signal?.addEventListener("abort", cancel, { once: true });
257
+ if (signal?.aborted) cancel();
258
+ });
222
259
  };
223
260
  const reserve = async (gate, weight, options) => {
224
261
  const releaseSupplemental = await gate(weight, options);
@@ -244,56 +281,80 @@ export function createRequestAdmission({
244
281
  },
245
282
  maxWeight: { value: releaseSupplemental.maxWeight },
246
283
  });
247
- supplementalReleases.add(releaseReservation);
284
+ (supplementalReleases ||= new Set()).add(releaseReservation);
248
285
  return releaseReservation;
249
286
  };
250
287
  release.acquireDecompression = (options) => acquireDecompression(1, options);
251
288
  release.reserveDecodedBody = (bytes, options) => reserve(acquireDecodedBody, bytes, options);
252
289
  release.reserveDecodedBody.supportsResize = true;
253
290
  release.reserveResponseHistory = (bytes, options) => reserve(acquireResponseHistory, bytes, options);
254
- entry.resolve(release);
291
+ return release;
255
292
  };
256
293
 
257
294
  const drain = () => {
295
+ if (growth) {
296
+ if (activeBytes + growth.extra > byteLimit) return;
297
+ growth.grant();
298
+ }
258
299
  for (let index = 0; index < queue.length;) {
259
300
  const entry = queue[index];
260
301
  if (entry.cancelled) {
261
302
  queue.splice(index, 1);
262
303
  continue;
263
304
  }
264
- if (activeBytes + entry.weight > byteLimit) {
265
- // Unknown-length requests reserve the whole budget. Once one is waiting,
266
- // do not let later arrivals keep extending its wait indefinitely.
267
- if (entry.weight === byteLimit) break;
305
+ if (activeBytes + entry.weight > byteLimit || entry.progressive && progressiveReader) {
306
+ // Preserve queue ordering for requests that need exclusive access.
307
+ if (!entry.progressive && entry.weight === byteLimit) break;
268
308
  index += 1;
269
309
  continue;
270
310
  }
271
311
  queue.splice(index, 1);
272
- activate(entry);
312
+ entry.cleanup();
313
+ const waitMs = Math.max(0, Date.now() - entry.startedAt);
314
+ counters.waitMsTotal += waitMs;
315
+ counters.waitMsMax = Math.max(counters.waitMsMax, waitMs);
316
+ recordWait(entry, "admitted", waitMs);
317
+ entry.resolve(activate(entry.weight, entry.progressive));
273
318
  }
274
319
  };
275
320
 
276
- const acquire = (req, { signal } = {}) => {
321
+ const acquire = (req, { signal, streamingBody = false } = {}) => {
277
322
  counters.total += 1;
278
323
  if (signal?.aborted) {
279
324
  counters.aborted += 1;
280
325
  return Promise.reject(admissionAbortError(signal));
281
326
  }
282
- const weight = requestAdmissionWeight(req, byteLimit);
283
- const blockedByExclusive = queue.some((entry) => !entry.cancelled && entry.weight === byteLimit);
284
- const mustWait = blockedByExclusive || activeBytes + weight > byteLimit;
285
- if (queue.length >= queueLimit && mustWait) {
327
+ const length = requestContentLength(req), lengthKnown = Number.isFinite(length) && length >= 0;
328
+ const progressive = streamingBody && !lengthKnown;
329
+ const weight = progressive ? 1 : requestAdmissionWeight(req, byteLimit, length);
330
+ const available = !growth && activeBytes + weight <= byteLimit && (!progressive || !progressiveReader);
331
+ if (queue.length === 0 && available) return Promise.resolve(activate(weight, progressive));
332
+ const blockedByExclusive = queue.some(entry => !entry.cancelled && !entry.progressive && entry.weight === byteLimit);
333
+ if (!blockedByExclusive && available) return Promise.resolve(activate(weight, progressive));
334
+ if (queue.length >= queueLimit) {
286
335
  counters.rejected += 1;
287
336
  return Promise.reject(httpError(`Request queue is full (${queueLimit} waiting)`, 503));
288
337
  }
289
- if (mustWait) counters.queued += 1;
290
-
338
+ counters.queued += 1;
339
+ const start = Date.now(), context = currentRequestContext();
340
+ const id = context?.requestId;
341
+ const evidence = {
342
+ ...(typeof id === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id) ? { request_id: id } : {}),
343
+ route: ADMISSION_ROUTES.has(context?.route) ? context.route : "other",
344
+ queued_at: new Date(start).toISOString(),
345
+ reason: growth ? "upload_growth" : blockedByExclusive ? "exclusive_waiter" : progressive && progressiveReader ? "upload_in_progress" : "body_budget",
346
+ requested_bytes: weight, active_bytes: activeBytes, limit_bytes: byteLimit,
347
+ length_known: lengthKnown,
348
+ };
291
349
  return new Promise((resolve, reject) => {
292
350
  let timer;
293
351
  const entry = {
294
352
  cancelled: false,
295
- startedAt: Date.now(),
353
+ startedAt: start,
354
+ evidence,
355
+ tracker: context?.streamPerformance,
296
356
  weight,
357
+ progressive,
297
358
  resolve,
298
359
  cleanup: () => {
299
360
  if (timer) clearTimeout(timer);
@@ -307,6 +368,7 @@ export function createRequestAdmission({
307
368
  if (reason === "timed_out") counters.timedOut += 1;
308
369
  entry.cleanup();
309
370
  remove(entry);
371
+ recordWait(entry, reason, Math.max(0, Date.now() - entry.startedAt));
310
372
  reject(error);
311
373
  drain();
312
374
  };
@@ -340,6 +402,9 @@ export function createRequestAdmission({
340
402
  ? Number((counters.waitMsTotal / counters.activated).toFixed(1))
341
403
  : 0,
342
404
  waitMsMax: counters.waitMsMax,
405
+ uploadWaitingForMemory: Boolean(growth),
406
+ longestWait: longestWait ? { ...longestWait } : null,
407
+ recentWaits: recentWaits.map(row => ({ ...row })),
343
408
  decompressionsActive: acquireDecompression.stats().activeRequests,
344
409
  decompressionsQueued: acquireDecompression.stats().queued,
345
410
  decodedBodyBytes: acquireDecodedBody.stats().activeRequestedWeight,
@@ -259,7 +259,7 @@ export function createResponsesHandler(options) {
259
259
  releaseRequest();
260
260
  };
261
261
  try {
262
- releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
262
+ releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal, streamingBody: true }));
263
263
  abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
264
264
  parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
265
265
  observeRequestedModel(parsed);
@@ -597,7 +597,7 @@ export function createResponsesCompactHandler(options) {
597
597
  releaseRequest();
598
598
  };
599
599
  try {
600
- releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
600
+ releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal, streamingBody: true }));
601
601
  abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
602
602
  const parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
603
603
  const context = currentRequestContext();if (context) { context.purpose = requestPurpose(req.headers["x-ccdx-purpose"], "compaction");context.streamPerformance?.setPurpose(context.purpose); }
@@ -3,7 +3,7 @@ import { controlImage } from "./image-control.mjs";
3
3
  import { controlCodexLaunch } from "./codex-launch-control.mjs";
4
4
  import { serviceSettingsSnapshot, servicePreferences, writeServicePreference,
5
5
  writeTerminalAnimationTheme, writeTerminalColorTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib,
6
- nightlyUpdatePreference, writeNightlyUpdatePreference, decodedBodyLimitPreference, writeDecodedBodyLimitMib } from "./user-settings.mjs";
6
+ nightlyUpdatePreference, writeNightlyUpdatePreference, decodedBodyLimitPreference, writeDecodedBodyLimitMib, inflightBodyLimitPreference, writeInflightBodyLimitMib, INFLIGHT_BODY_LIMIT_MIN_MIB, INFLIGHT_BODY_LIMIT_MAX_MIB } from "./user-settings.mjs";
7
7
  import { readPredictionSettings } from "./native-prediction-profile.mjs";
8
8
  import { cacheRuntimeSnapshot, cleanRuntimeCaches, setHistoryCacheLimit } from "./cache-control.mjs";
9
9
  import { isTerminalAnimationTheme } from "./terminal-animation.mjs";
@@ -46,7 +46,7 @@ export function createServiceControl({ env = process.env, home, platform = proce
46
46
  return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: localPrivacy,
47
47
  applications: applicationControl.snapshot(),
48
48
  features: { prediction: { ...featureSnapshot(predictionControlSnapshot), bridge: prediction?.bridge || "stopped", active: prediction?.active === true }, image: { ...image, runtime: imageHostState.snapshot() } },
49
- decoded_body: decodedBodyLimitPreference(options), manual_update: { available: typeof manualUpdate === "function" }, last_operation: lastOperation,
49
+ decoded_body: decodedBodyLimitPreference(options), inflight_body: inflightBodyLimitPreference(options), manual_update: { available: typeof manualUpdate === "function" }, last_operation: lastOperation,
50
50
  ...(providerRuntime?.errorCaptureSnapshot ? { error_capture: providerRuntime.errorCaptureSnapshot() } : {}),
51
51
  ...(providerRuntime?.compaction ? { compaction: providerRuntime.compaction.snapshot() } : {}),
52
52
  nightly_update: { enabled, ...nightly, effect: enabled && !nightly ? "next_start" : "immediate" },
@@ -70,7 +70,7 @@ export function createServiceControl({ env = process.env, home, platform = proce
70
70
  prediction: ["action", "operation"], image: ["action", "operation", "model", "evidence", "confirmed"],
71
71
  codex_app: ["action", "operation", "intent", "confirmed"],
72
72
  application: ["action", "id", "operation", "confirmed", "fresh", "expected_pid", "expected_started"],
73
- update: ["action", "confirmed"], decoded_limit: ["action", "mib"],
73
+ update: ["action", "confirmed"], decoded_limit: ["action", "mib"], inflight_body_limit: ["action", "mib"],
74
74
  error_capture: ["action", "operation", "source", "model"],
75
75
  preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
76
76
  provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
@@ -99,6 +99,12 @@ export function createServiceControl({ env = process.env, home, platform = proce
99
99
  } else if (input.action === "decoded_limit") {
100
100
  if (decodedBodyLimitPreference(options).source === "environment") throw new Error("Request limit is controlled by the launch environment");
101
101
  writeDecodedBodyLimitMib(input.mib, options);
102
+ } else if (input.action === "inflight_body_limit") {
103
+ if (inflightBodyLimitPreference(options).source === "environment") throw Object.assign(new Error("Request limit is controlled by the launch environment"), { code: "ccdx_inflight_limit_environment", statusCode: 409 });
104
+ if (input.mib !== null && (!Number.isSafeInteger(input.mib) || input.mib < INFLIGHT_BODY_LIMIT_MIN_MIB || input.mib > INFLIGHT_BODY_LIMIT_MAX_MIB)) {
105
+ throw Object.assign(new Error(`Shared request-body limit must be an integer from ${INFLIGHT_BODY_LIMIT_MIN_MIB} to ${INFLIGHT_BODY_LIMIT_MAX_MIB} MiB`), { code: "ccdx_inflight_limit_invalid", statusCode: 400 });
106
+ }
107
+ writeInflightBodyLimitMib(input.mib, options);
102
108
  } else if (["preferences", "reset_preferences", "restore_preferences"].includes(input.action)) {
103
109
  if (input.action === "preferences" && Object.hasOwn(input.values || {}, "privacy_enabled")
104
110
  && input.values.privacy_enabled !== settingsPreferencesSnapshot(options).values.privacy_enabled) {
@@ -142,14 +142,18 @@ export function createSourceAdmission({ now = Date.now, initialLimit = MAX_LIMIT
142
142
  streamFailure(error, headers) { const value = sourceLimitFeedback(429, headers, { error }, now());if (value?.kind !== "unknown") this.limit(value); }
143
143
  observe(status, headers, body) {
144
144
  const group = this.group, entry = this;
145
- this.responseAt ??= now();
146
- const declared = headers?.get?.("x-ratelimit-concurrency-limit");
147
- if (!this.headersObserved && /^\d{1,3}$/.test(declared || "") && validLimit(Number(declared))) {
148
- group.advertised = Number(declared);group.advertisedUntil = now() + stableMs;group.limit = Math.min(group.limit, group.advertised);
145
+ if (!this.headersObserved) {
146
+ this.headersObserved = true;
147
+ const declared = headers?.get?.("x-ratelimit-concurrency-limit");
148
+ if (declared && /^\d{1,3}$/.test(declared) && validLimit(Number(declared))) {
149
+ group.advertised = Number(declared);group.advertisedUntil = now() + stableMs;group.limit = Math.min(group.limit, group.advertised);
150
+ }
149
151
  }
150
- this.headersObserved = true;this.observed ||= status === 429;
152
+ if (status !== 429) return;
153
+ this.responseAt ??= now();
154
+ this.observed = true;
151
155
  const value = sourceLimitFeedback(status, headers, body, this.responseAt);
152
- if (value) value.delay = Math.max(0, this.responseAt + value.delay - now());
156
+ value.delay = Math.max(0, this.responseAt + value.delay - now());
153
157
  feedback(group, entry, value);
154
158
  }
155
159
  release(success = false) {
@@ -357,6 +357,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
357
357
  attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
358
358
  observeContext(values) {
359
359
  if (finished || !values || typeof values !== "object") return;
360
+ if (values.body_queue) context.body_queue = values.body_queue;
360
361
  if (Number.isSafeInteger(values.source_queue_ms) && values.source_queue_ms >= 0) context.source_queue_ms = values.source_queue_ms;
361
362
  if (values.delivery_cancelled === 1) context.delivery_cancelled = 1;
362
363
  if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
@@ -23,6 +23,9 @@ const AUTO_REVIEW_REASONING_KEY = "auto_review_reasoning";
23
23
  const TERMINAL_ANIMATION_KEY = "terminal_animation";
24
24
  const RESPONSE_HISTORY_MAX_MIB_KEY = "response_history_max_mib";
25
25
  const DECODED_BODY_LIMIT_MIB_KEY = "decoded_body_limit_mib";
26
+ const INFLIGHT_BODY_LIMIT_MIB_KEY = "inflight_body_limit_mib";
27
+ export const INFLIGHT_BODY_LIMIT_MIN_MIB = RUNTIME_DEFAULTS.maxInflightBodyBytes / MIB;
28
+ export const INFLIGHT_BODY_LIMIT_MAX_MIB = 128;
26
29
  const SERVICE_FLAGS = ["terminal_animation_enabled", "open_webui", "image_enabled", "prediction_enabled", "context_compaction_enabled", "codex_auto_launch"];
27
30
  export const DECODED_BODY_LIMIT_MIN_MIB = RUNTIME_DEFAULTS.maxDecodedBodyBytes / MIB;
28
31
  export const DECODED_BODY_LIMIT_MAX_MIB = 512;
@@ -107,6 +110,10 @@ export function readUserSettings({ env = process.env, home = os.homedir(), stric
107
110
  delete parsed[DECODED_BODY_LIMIT_MIB_KEY];
108
111
  }
109
112
  }
113
+ if (Object.hasOwn(parsed, INFLIGHT_BODY_LIMIT_MIB_KEY) && !validInflightBodyLimit(parsed[INFLIGHT_BODY_LIMIT_MIB_KEY])) {
114
+ if (strict) throw invalidSettings(filePath, `${INFLIGHT_BODY_LIMIT_MIB_KEY} must be an integer from ${INFLIGHT_BODY_LIMIT_MIN_MIB} to ${INFLIGHT_BODY_LIMIT_MAX_MIB}`);
115
+ delete parsed[INFLIGHT_BODY_LIMIT_MIB_KEY];
116
+ }
110
117
  return parsed;
111
118
  } catch (error) {
112
119
  if (error?.code === "ENOENT") return {};
@@ -215,6 +222,33 @@ function historyLimitPreference(settings, env) {
215
222
  return { bytes: RESPONSE_HISTORY_DEFAULT_MIB * MIB, mib: RESPONSE_HISTORY_DEFAULT_MIB, source: "default" };
216
223
  }
217
224
 
225
+ const validInflightBodyLimit = mib => Number.isSafeInteger(mib)
226
+ && mib >= INFLIGHT_BODY_LIMIT_MIN_MIB && mib <= INFLIGHT_BODY_LIMIT_MAX_MIB;
227
+
228
+ export function inflightBodyLimitPreference({ env = process.env, home = os.homedir() } = {}) {
229
+ if (String(env.CCDX_MAX_INFLIGHT_BODY_BYTES || "").trim()) {
230
+ return { bytes: loadRuntimeConfig(env).maxInflightBodyBytes, source: "environment" };
231
+ }
232
+ const mib = readUserSettings({ env, home })[INFLIGHT_BODY_LIMIT_MIB_KEY];
233
+ if (mib !== undefined) return { bytes: mib * MIB, mib, source: "settings" };
234
+ return { bytes: RUNTIME_DEFAULTS.maxInflightBodyBytes, mib: INFLIGHT_BODY_LIMIT_MIN_MIB, source: "default" };
235
+ }
236
+
237
+ export function writeInflightBodyLimitMib(mib, options = {}) {
238
+ if (mib !== null && !validInflightBodyLimit(mib)) {
239
+ throw new Error(`Shared request-body limit must be an integer from ${INFLIGHT_BODY_LIMIT_MIN_MIB} to ${INFLIGHT_BODY_LIMIT_MAX_MIB} MiB`);
240
+ }
241
+ const filePath = userSettingsPath(options);
242
+ return withFileLockSync(`${filePath}.lock`, () => {
243
+ const next = readUserSettings({ ...options, strict: true });
244
+ if (mib === null) {
245
+ if (!Object.hasOwn(next, INFLIGHT_BODY_LIMIT_MIB_KEY)) return false;
246
+ delete next[INFLIGHT_BODY_LIMIT_MIB_KEY];
247
+ } else next[INFLIGHT_BODY_LIMIT_MIB_KEY] = mib;
248
+ return atomicWriteFileIfChangedSync(filePath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
249
+ });
250
+ }
251
+
218
252
  export function decodedBodyLimitPreference({ env = process.env, home = os.homedir() } = {}) {
219
253
  const environment = String(env.CCDX_MAX_DECODED_BODY_BYTES || "").trim();
220
254
  if (environment) {