codex-copilot-dx 1.4.6 → 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,9 +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
+ 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
+
261
263
  `ccdx status` shows the longest admitted wait in the gateway's local request-body queue. `status --json` retains the longest sample and up to 16 recent waits, including cancellations and timeouts. Samples record a route, request ID, wait reason and byte counts in memory; no request body or credential is retained. The existing request details distinguish local waiting from waiting for the selected source. Local waiting ends before the body is read, and source waiting ends before sending upstream.
262
264
 
263
- 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.
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.
264
266
 
265
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.
266
268
 
@@ -810,7 +812,7 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
810
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 |
811
813
  | `CCDX_MAX_BODY_BYTES` | `67108864` | Maximum compressed or raw request-body size |
812
814
  | `CCDX_MAX_DECODED_BODY_BYTES` | `134217728` | Maximum decoded request-body size after decompression |
813
- | `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 |
814
816
  | `CCDX_MAX_UPSTREAM_CHAT_RESPONSE_BYTES` | `67108864` | Maximum buffered successful Chat Completions response used by the internal Responses compatibility path |
815
817
  | `CCDX_MAX_UPSTREAM_RESPONSES_RESPONSE_BYTES` | `268435456` | Maximum buffered successful native Responses or compact response; streaming Responses use bounded backpressure |
816
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.6",
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();
@@ -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";
@@ -8,7 +8,7 @@ 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
13
  let upstream;
14
14
  {
@@ -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 };
@@ -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,11 +1017,18 @@
1014
1017
  "requested_model": ["Requested model", "指定模型"],
1015
1018
  "request_kind": ["Request purpose", "请求用途"],
1016
1019
  "attempt_timings": ["Send attempts", "发送次数"],
1017
- "body_queue_wait": ["Local queue", "本机排队"],
1020
+ "body_queue_wait": ["Local queue history", "本机排队记录"],
1018
1021
  "source_queue_wait": ["Source queue", "来源排队"],
1019
- "body_queue_detail": ["{ms} ms · {reason} · needs {reserved} · used {occupied}/{limit}", "{ms} ms · {reason} · 需 {reserved} · 已用 {occupied}/{limit}"],
1020
- "body_queue_exclusive": ["Exclusive request ahead", "前方请求需独占"],
1021
- "body_queue_budget": ["Memory budget", "内存额度不足"],
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", "剩余额度不足以预留本请求"],
1022
1032
  "gateway_timing_output_speed_is_estimated": ["Estimated by CCDX. Not internal model time or total throughput.", "由 CCDX 估算。\n不代表模型内部耗时或总吞吐。"],
1023
1033
  "value_samples_samples": ["{value} / {samples} samples", "{value} / {samples}次样本"],
1024
1034
  "ccdx_local_dashboard": ["CCDX · Dashboard", "CCDX · 运行面板"],
@@ -400,11 +400,17 @@
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 }) : "—"],
405
- ...(Number.isSafeInteger(context.body_queue?.wait_ms) ? [["body_queue_wait", phrase("body_queue_detail", {
406
- ms: number(context.body_queue.wait_ms), reason: phrase(context.body_queue.reason === "exclusive_waiter" ? "body_queue_exclusive" : "body_queue_budget"),
407
- reserved: mib(context.body_queue.requested_bytes), occupied: mib(context.body_queue.active_bytes), limit: mib(context.body_queue.limit_bytes),
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),
408
414
  })]] : []),
409
415
  ...(Number.isSafeInteger(context.source_queue_ms) ? [["source_queue_wait", `${number(context.source_queue_ms)} ms`]] : []),
410
416
  ["wire_mib", finite(context.payload_bytes) ? `${(Number(context.payload_bytes) / 1048576).toFixed(2)} MiB` : "—"],
@@ -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));
@@ -199,9 +212,9 @@ export async function readJsonBody(req, {
199
212
  if (signal?.aborted) throw admissionAbortError(signal);
200
213
  const encoding = req.headers?.["content-encoding"];
201
214
  if (!encoding || encoding === "identity" || contentEncodings(encoding).every(value => value === "identity")) {
202
- return parse(await readIdentityText(req, maxBodyBytes, maxDecodedBodyBytes, signal, bytes => admission?.resize?.(bytes)));
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;
@@ -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;
@@ -21,8 +21,7 @@ export function requestContentLength(req) {
21
21
  return Number.parseInt(req.headers?.["content-length"] || "", 10);
22
22
  }
23
23
 
24
- function requestAdmissionWeight(req, maxBytes) {
25
- const contentLength = requestContentLength(req);
24
+ function requestAdmissionWeight(req, maxBytes, contentLength) {
26
25
  if (!Number.isFinite(contentLength) || contentLength < 0) return maxBytes;
27
26
  const encoding = req.headers?.["content-encoding"];
28
27
  const compressed = encoding && encoding !== "identity" && contentEncodings(encoding).some(value => value !== "identity");
@@ -154,10 +153,12 @@ function createSupplementalAdmission({ maxWeight, maxQueued, waitTimeoutMs, labe
154
153
 
155
154
  export function createRequestAdmission({
156
155
  maxBytes = MAX_INFLIGHT_BODY_BYTES,
156
+ maxSupplementalBytes = maxBytes,
157
157
  maxQueued = MAX_QUEUED_REQUESTS,
158
158
  waitTimeoutMs = REQUEST_QUEUE_TIMEOUT_MS,
159
159
  } = {}) {
160
160
  const byteLimit = parsePositiveInteger(maxBytes, MAX_INFLIGHT_BODY_BYTES);
161
+ const supplementalByteLimit = parsePositiveInteger(maxSupplementalBytes, byteLimit);
161
162
  const queueLimit = parsePositiveInteger(maxQueued, MAX_QUEUED_REQUESTS);
162
163
  const timeoutMs = parsePositiveInteger(waitTimeoutMs, REQUEST_QUEUE_TIMEOUT_MS);
163
164
  const acquireDecompression = createSupplementalAdmission({
@@ -167,14 +168,14 @@ export function createRequestAdmission({
167
168
  label: "Request decompression",
168
169
  });
169
170
  const acquireDecodedBody = createSupplementalAdmission({
170
- maxWeight: byteLimit,
171
+ maxWeight: supplementalByteLimit,
171
172
  maxQueued: queueLimit,
172
173
  waitTimeoutMs: timeoutMs,
173
174
  label: "Decoded request body",
174
175
  blockBehindExclusive: true,
175
176
  });
176
177
  const acquireResponseHistory = createSupplementalAdmission({
177
- maxWeight: byteLimit,
178
+ maxWeight: supplementalByteLimit,
178
179
  maxQueued: queueLimit,
179
180
  waitTimeoutMs: timeoutMs,
180
181
  label: "Response history",
@@ -182,6 +183,10 @@ export function createRequestAdmission({
182
183
  const queue = [];
183
184
  let activeBytes = 0;
184
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;
185
190
  const recentWaits = [];
186
191
  let longestWait = null;
187
192
  function recordWait(entry, outcome, waitMs) {
@@ -207,8 +212,10 @@ export function createRequestAdmission({
207
212
  if (index >= 0) queue.splice(index, 1);
208
213
  };
209
214
 
210
- const activate = (weight) => {
215
+ const activate = (weight, progressive) => {
211
216
  activeBytes += weight;
217
+ if (progressive) progressiveReader = true;
218
+ let reading = progressive;
212
219
  activeRequests += 1;
213
220
  counters.activated += 1;
214
221
  let released = false;
@@ -216,6 +223,10 @@ export function createRequestAdmission({
216
223
  const release = () => {
217
224
  if (released) return;
218
225
  released = true;
226
+ if (reading) {
227
+ growth?.cancel();
228
+ reading = progressiveReader = false;
229
+ }
219
230
  if (supplementalReleases) {
220
231
  for (const releaseSupplemental of supplementalReleases) releaseSupplemental();
221
232
  supplementalReleases.clear();
@@ -227,9 +238,25 @@ export function createRequestAdmission({
227
238
  release.resize = bytes => {
228
239
  if (released || !Number.isSafeInteger(bytes) || bytes < 0) return;
229
240
  const next = Math.max(1, Math.min(weight, bytes));
230
- if (next === weight) return;
241
+ if (!reading && next === weight) return;
242
+ if (reading) reading = progressiveReader = false;
231
243
  activeBytes -= weight - next;weight = next;drain();
232
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
+ });
259
+ };
233
260
  const reserve = async (gate, weight, options) => {
234
261
  const releaseSupplemental = await gate(weight, options);
235
262
  if (released) {
@@ -265,16 +292,19 @@ export function createRequestAdmission({
265
292
  };
266
293
 
267
294
  const drain = () => {
295
+ if (growth) {
296
+ if (activeBytes + growth.extra > byteLimit) return;
297
+ growth.grant();
298
+ }
268
299
  for (let index = 0; index < queue.length;) {
269
300
  const entry = queue[index];
270
301
  if (entry.cancelled) {
271
302
  queue.splice(index, 1);
272
303
  continue;
273
304
  }
274
- if (activeBytes + entry.weight > byteLimit) {
275
- // Unknown-length requests reserve the whole budget. Once one is waiting,
276
- // do not let later arrivals keep extending its wait indefinitely.
277
- 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;
278
308
  index += 1;
279
309
  continue;
280
310
  }
@@ -284,20 +314,23 @@ export function createRequestAdmission({
284
314
  counters.waitMsTotal += waitMs;
285
315
  counters.waitMsMax = Math.max(counters.waitMsMax, waitMs);
286
316
  recordWait(entry, "admitted", waitMs);
287
- entry.resolve(activate(entry.weight));
317
+ entry.resolve(activate(entry.weight, entry.progressive));
288
318
  }
289
319
  };
290
320
 
291
- const acquire = (req, { signal } = {}) => {
321
+ const acquire = (req, { signal, streamingBody = false } = {}) => {
292
322
  counters.total += 1;
293
323
  if (signal?.aborted) {
294
324
  counters.aborted += 1;
295
325
  return Promise.reject(admissionAbortError(signal));
296
326
  }
297
- const weight = requestAdmissionWeight(req, byteLimit);
298
- if (queue.length === 0 && activeBytes + weight <= byteLimit) return Promise.resolve(activate(weight));
299
- const blockedByExclusive = queue.some((entry) => !entry.cancelled && entry.weight === byteLimit);
300
- if (!blockedByExclusive && activeBytes + weight <= byteLimit) return Promise.resolve(activate(weight));
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));
301
334
  if (queue.length >= queueLimit) {
302
335
  counters.rejected += 1;
303
336
  return Promise.reject(httpError(`Request queue is full (${queueLimit} waiting)`, 503));
@@ -305,14 +338,13 @@ export function createRequestAdmission({
305
338
  counters.queued += 1;
306
339
  const start = Date.now(), context = currentRequestContext();
307
340
  const id = context?.requestId;
308
- const length = requestContentLength(req);
309
341
  const evidence = {
310
342
  ...(typeof id === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id) ? { request_id: id } : {}),
311
343
  route: ADMISSION_ROUTES.has(context?.route) ? context.route : "other",
312
344
  queued_at: new Date(start).toISOString(),
313
- reason: blockedByExclusive ? "exclusive_waiter" : "body_budget",
345
+ reason: growth ? "upload_growth" : blockedByExclusive ? "exclusive_waiter" : progressive && progressiveReader ? "upload_in_progress" : "body_budget",
314
346
  requested_bytes: weight, active_bytes: activeBytes, limit_bytes: byteLimit,
315
- length_known: Number.isFinite(length) && length >= 0,
347
+ length_known: lengthKnown,
316
348
  };
317
349
  return new Promise((resolve, reject) => {
318
350
  let timer;
@@ -322,6 +354,7 @@ export function createRequestAdmission({
322
354
  evidence,
323
355
  tracker: context?.streamPerformance,
324
356
  weight,
357
+ progressive,
325
358
  resolve,
326
359
  cleanup: () => {
327
360
  if (timer) clearTimeout(timer);
@@ -369,6 +402,7 @@ export function createRequestAdmission({
369
402
  ? Number((counters.waitMsTotal / counters.activated).toFixed(1))
370
403
  : 0,
371
404
  waitMsMax: counters.waitMsMax,
405
+ uploadWaitingForMemory: Boolean(growth),
372
406
  longestWait: longestWait ? { ...longestWait } : null,
373
407
  recentWaits: recentWaits.map(row => ({ ...row })),
374
408
  decompressionsActive: acquireDecompression.stats().activeRequests,
@@ -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) {
@@ -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) {