Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ commandcode/
| `CC_DEVICE_PROJECT_DIR` | empty | Faked project directory → `deviceProjectDir` |
| `CC_EMPTY_SYSTEM_PLACEHOLDER` | `true` | Space placeholder for a missing system prompt; `false` disables → `emptySystemPlaceholder` |
| `CC_MAX_BODY_MB` | `100` | Max request body size in MB; oversized requests get `413` |
| `CC_MAX_TOOL_IMAGE_MB` | `6` | Total per-request budget for tool screenshots (base64); older ones become a placeholder; `0` disables. See [Tool screenshot budget](#tool-screenshot-budget) |
| `CC_STREAM_IDLE_MS` | `30000` | Streaming upstream read idle timeout; see [Upstream idle timeouts](#upstream-idle-timeouts) |
| `CC_NONSTREAM_IDLE_MS` | `90000` | Non-streaming upstream read idle timeout |
| `CC_MAX_INFLIGHT` | `0` (unlimited) | In-process request cap; over-limit returns `503`; see [In-flight cap](#in-flight-cap-optional) |
Expand All @@ -101,6 +102,28 @@ authority for actual retention and provider availability.

> ⚠️ **Memory amplification**: a request body exists in several copies before it reaches upstream; measured peak ≈ body size × **5.1–7.4** (7 MB → +52 MB, 20 MB → +116 MB, while a request rejected with `413` costs only ×1.05). The default `CC_MAX_BODY_MB=100` therefore implies up to ~550 MB for a **single** request, and that limit is per-request, not global. See [Memory & Deployment](#memory--deployment).

### Tool screenshot budget

Images inside tool results are sent upstream as **separate** `image` blocks (an `input_image` inside
`function_call_output.output` is no longer `JSON.stringify`-ed into the tool-result text). Base64 is extremely
expensive once upstream tokenizes it as **text** — a single 2.76 MB Codex Desktop screenshot measured
≈ **1.92M tokens**, blowing straight through a 1M window:

```
400 This model's maximum context length is 1048576 tokens. However, you requested
1986800 tokens (1922800 in the messages, 64000 in the completion)
```

Images are still **re-sent in full every turn**: one real session carried 11 screenshots ≈5.5 MB of base64,
which — with the memory amplification above (×5.1–7.4) — pushed the proxy to `anon-rss 532 MB` and triggered a
**global OOM** on a 1 GB box. `CC_MAX_TOOL_IMAGE_MB` (default `6`) keeps the **newest** images within budget
(at least one) and replaces the rest with `[older tool screenshot omitted: image budget exceeded]`, so the model
knows an image was dropped instead of assuming none ever existed. Only tool screenshots are affected; images
you attach yourself are untouched.

> Raise the budget if the model really needs every screenshot, but size memory as `budget × in-flight × 5–7`
> (see [in-flight cap](#in-flight-cap-optional)).

### Upstream proxy (`upstreamProxy` / `CC_UPSTREAM_PROXY`)

Route the requests the proxy makes **to Command Code** through a local HTTP proxy — for egress-region switching, or for comparing IPs when debugging risk-control `403`s.
Expand Down Expand Up @@ -294,6 +317,7 @@ The request side is translated: `input` (message array; items may omit `type`),
- **Stateless**: `previous_response_id` is not supported and answers `400` — send the full `input` every turn (the proxy stores no conversation history).
- Errors use the Responses shape: `{"error":{"message":...,"type":...}}`.
- Shares the same upstream call path, cache breakpoints and idle watchdog as `/v1/chat/completions`.
- **First-token silence and keep-alive**: `response.created` / `response.in_progress` are emitted **immediately** once upstream returns `200`, and a `: keepalive` SSE comment follows every 5 s while waiting. Time-to-first-token for a reasoning model with a large prompt measured 15–40 s; that silent window used to put **zero bytes** on the wire, so intermediate layers (EdgeOne's origin idle timeout measured ~15 s) or client first-byte timeouts cut the connection — visible as nginx `499` with `body_bytes_sent=0` and a client retrying every 15 s. SSE comments must be ignored by clients per spec (`/v1/messages` uses `event: ping`, but Responses has no ping event and an unknown event type risks strict-parser errors).

```bash
curl http://127.0.0.1:3050/v1/responses \
Expand Down
21 changes: 21 additions & 0 deletions README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ commandcode/
| `CC_DEVICE_PROJECT_DIR` | 空 | 伪装的项目目录 → `deviceProjectDir` |
| `CC_EMPTY_SYSTEM_PLACEHOLDER` | `true` | 无 system prompt 时发空格占位;`false` 关掉 → `emptySystemPlaceholder` |
| `CC_MAX_BODY_MB` | `100` | 请求体上限(MB),超限返回 `413` |
| `CC_MAX_TOOL_IMAGE_MB` | `6` | 单请求内工具截图(base64)总预算,超预算的老图换成占位;`0` 关闭,见[工具截图预算](#工具截图预算) |
| `CC_STREAM_IDLE_MS` | `30000` | 流式上游读空闲超时,见[上游空闲超时](#上游空闲超时) |
| `CC_NONSTREAM_IDLE_MS` | `90000` | 非流式上游读空闲超时(同上)|
| `CC_MAX_INFLIGHT` | `0`(不限)| 进程内在途请求上限,超限 `503`,见[在途上限](#在途请求上限可选) |
Expand All @@ -99,6 +100,25 @@ header。该开关只是请求 Command Code 使用 ZDR-only 路由,实际数

> ⚠️ **内存放大**:请求体在转发到上游前会存在多份副本,实测峰值 ≈ body 大小 × **5.1~7.4**(7MB→+52MB、20MB→+116MB;被 `413` 拒绝的请求只要 ×1.05)。因此默认 `CC_MAX_BODY_MB=100` 意味着**单个请求**最坏可吃 ~550MB,且该上限是每请求的、不是全局的。详见[内存与部署](#内存与部署)。

### 工具截图预算

工具结果里的图片会**单独**作为 `image` 块发给上游(`function_call_output.output` 里的 `input_image`
不再被 `JSON.stringify` 进 tool-result 文本)。原因是 base64 一旦被上游按**文本**分词就极其昂贵 ——
真机实测 Codex Desktop 单张 2.76MB 截图 ≈ **1.92M token**,直接撞穿模型的 1M 窗口:

```
400 This model's maximum context length is 1048576 tokens. However, you requested
1986800 tokens (1922800 in the messages, 64000 in the completion)
```

但图片仍会随每一轮请求**全量重传**:真机实测一个会话里 11 张截图 ≈5.5MB base64,配合上面的内存放大
×5.1~7.4,在 1GB 的机器上足以把代理顶到 `anon-rss 532MB` 并触发 **global OOM**(内核杀掉 node,
整机假死)。`CC_MAX_TOOL_IMAGE_MB`(默认 `6`)按**从新到旧**保留到预算之内(至少保一张),被裁掉的
替换成 `[older tool screenshot omitted: image budget exceeded]` —— 模型知道有图被丢,不会以为历史里
本来就没图。只作用于工具截图,用户自己贴的图不受影响。

> 想让模型看到全部截图就调大预算,但请按 `预算 × 并发 × 5~7` 估内存(并发见[在途上限](#在途请求上限可选))。

### 上游代理(`upstreamProxy` / `CC_UPSTREAM_PROXY`)

让代理**发往 Command Code 的请求**走本地 HTTP 代理 —— 用于出口地区调整,或排查风控 `403` 时做 IP 维度对照。
Expand Down Expand Up @@ -292,6 +312,7 @@ OpenAI **Responses API**(Codex、以及新版 OpenAI SDK 用的那套)。
- **无状态**:`previous_response_id` 不支持,传了直接 `400` —— 每轮把完整 `input` 发过来即可(代理不存会话历史)。
- 错误体是 Responses 风格:`{"error":{"message":...,"type":...}}`。
- 与 `/v1/chat/completions` 共用同一套上游调用、缓存断点与空闲看门狗。
- **首字静默与保活**:拿到上游 `200` 后**立刻**下发 `response.created` / `response.in_progress`,此后等待期间每 5s 发一条 SSE 注释行 `: keepalive`。reasoning 模型 + 大 prompt 的首字实测 15~40s,这段静默期此前**零字节出网**,会被中间层(实测 EdgeOne 源站空闲超时约 15s)或客户端首字节超时掐断 —— 现象是 nginx 侧 `499`、`body_bytes_sent=0`、客户端每 15 秒重试一次。注释行按 SSE 规范必须被客户端忽略(`/v1/messages` 用的是 `event: ping`,Responses 没有 ping 事件,塞未知 event 类型有被严格解析器判错的风险)。

```bash
curl http://127.0.0.1:3050/v1/responses \
Expand Down
155 changes: 150 additions & 5 deletions proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2630,6 +2630,101 @@ function responsesTextOf(content) {
return content.map(p => (p && typeof p === 'object' ? (p.text || '') : '')).join('');
}

// data URL 图片:一段文本里超过这个长度的 data URL 就当成"图",提出来单独发;小图留在文本里
const INLINE_IMAGE_MIN = 256 * 1024;
// 单张 data URL 上限:再大就不要了,只留一句占位说明(既撑爆上游窗口,也撑爆内存)
const MAX_TOOL_IMAGE_URL = 12 * 1024 * 1024;
const DATA_URL_RE = /data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi;

// 从一段文本里捞出体积可观的 data URL 图片,原地替换成 [image] 占位。
// 必要性:base64 一旦被上游按**文本**分词就极其昂贵 —— 真机实测单张 2.76MB 截图 ≈ 1.92M token。
function extractInlineImages(text) {
const images = [];
const stripped = String(text).replace(DATA_URL_RE, (url) => {
if (url.length < INLINE_IMAGE_MIN) return url; // 小图留文本,别把工具输出切碎
if (url.length > MAX_TOOL_IMAGE_URL) return '[image omitted: too large]';
images.push(url);
return '[image]';
});
return { text: stripped, images };
}

// Responses 的 function_call_output.output 可能是字符串,也可能是内容块数组;后者能带图。
// Codex Desktop 的截图工具就是 [{type:'input_image', image_url:'data:image/png;base64,...'}]。
// 返回 { text, images },images 为 data URL 字符串数组。
function splitToolOutput(output) {
if (output === undefined || output === null) return { text: '', images: [] };
const texts = [];
const images = [];
const pushText = (raw) => {
const r = extractInlineImages(raw);
if (r.text) texts.push(r.text);
images.push(...r.images);
};
if (typeof output === 'string') {
pushText(output);
} else if (Array.isArray(output)) {
for (const part of output) {
if (!part) continue;
if (part.type === 'input_image' || part.type === 'image_url') {
const url = typeof part.image_url === 'string' ? part.image_url : (part.image_url && part.image_url.url) || '';
if (url.startsWith('data:')) {
if (url.length <= MAX_TOOL_IMAGE_URL) images.push(url);
else texts.push('[image omitted: too large]');
} else if (url) {
texts.push(`[image: ${url}]`); // 外链图上游不认,只能留个说明
}
} else if (typeof part.text === 'string') {
pushText(part.text);
} else {
pushText(JSON.stringify(part)); // 未知块保持原样,与旧行为一致
}
}
} else {
pushText(JSON.stringify(output));
}
return { text: texts.filter(Boolean).join('\n'), images };
}
// 单条请求内"工具截图"的总字节预算。工具截图会随每一轮请求全量重传,是内存与首字延迟的
// 头号杀手:真机实测一个 Codex 会话里 11 张截图 ≈5.5MB base64,配合 README 记录的内存放大
// ×5.1~7.4,把 1GB 的机器打到 global OOM(node anon-rss 532MB,内核把整机拖死)。
// 策略:从**最新**往回保留,预算内照发,超预算的老图替换成占位说明 —— 让模型知道有图被丢,
// 而不是以为历史里本来就没图。CC_MAX_TOOL_IMAGE_MB=0 关闭该行为。
const MAX_TOOL_IMAGE_BYTES = (() => {
const mb = Number.parseFloat(process.env.CC_MAX_TOOL_IMAGE_MB ?? '6');
return Number.isFinite(mb) && mb > 0 ? Math.round(mb * 1024 * 1024) : 0;
})();

function trimToolImages(messages) {
if (!MAX_TOOL_IMAGE_BYTES) return;
const refs = [];
for (const m of messages) {
if (!Array.isArray(m.content)) continue;
for (const part of m.content) if (part && part._toolImage) refs.push({ m, part });
}
if (!refs.length) return;
const keep = new Set();
let used = 0;
for (let i = refs.length - 1; i >= 0; i--) { // 从最新往回挑,至少保一张
const len = (refs[i].part.image_url && refs[i].part.image_url.url || '').length;
if (keep.size === 0 || used + len <= MAX_TOOL_IMAGE_BYTES) { keep.add(i); used += len; }
}
if (keep.size === refs.length) return; // 没超预算,原样不动
let droppedBytes = 0;
for (let i = 0; i < refs.length; i++) {
if (keep.has(i)) continue;
const idx = refs[i].m.content.indexOf(refs[i].part);
if (idx === -1) continue;
droppedBytes += (refs[i].part.image_url && refs[i].part.image_url.url || '').length;
refs[i].m.content[idx] = { type: 'text', text: '[older tool screenshot omitted: image budget exceeded]' };
}
log('warn', 'Tool images trimmed to budget', {
total: refs.length, kept: keep.size, dropped: refs.length - keep.size,
keptBytes: used, droppedBytes, budgetBytes: MAX_TOOL_IMAGE_BYTES,
});
}


function responsesReasoningOf(item) {
if (!item) return '';
if (Array.isArray(item.summary) && item.summary.length) return item.summary.map(p => (p && p.text) || '').join('');
Expand Down Expand Up @@ -2703,11 +2798,26 @@ function convertResponsesToChat(respReq) {
}
case 'function_call_output': {
flushPending();
messages.push({
role: 'tool',
tool_call_id: item.call_id || '',
content: typeof item.output === 'string' ? item.output : JSON.stringify(item.output === undefined ? '' : item.output),
});
// 工具结果里可能带图(Codex Desktop 截图工具即 output=[{type:'input_image', image_url:'data:image/png;base64,...'}])。
// 绝不能 JSON.stringify 成文本送上游:base64 会按文本分词,真机实测单张 2.76MB 截图 ≈ 1.92M token,
// 直接撞穿模型 1M 窗口("maximum context length is 1048576 tokens ... 1922800 in the messages")。
// 官方 CLI 的排布是:tool-result 只放文本,图片提出来放进紧跟其后的一条 user 消息
// (见 command-code@1.66.0 dist/cli.mjs 的 convertUserMessage / tool_result 分支)。
const { text, images } = splitToolOutput(item.output);
messages.push({ role: 'tool', tool_call_id: item.call_id || '', content: text });
if (images.length) {
log('info', 'Hoisted tool-output images to user message', {
count: images.length, bytes: images.reduce((a, u) => a + u.length, 0),
});
// content 走 image_url 形态,交给 buildCcRequest 里已验证的 user 图片分支转成 CC 的 {type:'image',image,mimeType}
messages.push({
role: 'user',
content: [
{ type: 'text', text: '[image returned by tool call]' },
...images.map(url => ({ type: 'image_url', image_url: { url }, _toolImage: true })),
],
});
}
break;
}
default: {
Expand All @@ -2719,6 +2829,9 @@ function convertResponsesToChat(respReq) {
}
flushPending();

// 统一裁剪工具截图(此时所有 item 都已转成 chat 形态,按顺序处理最直观)
trimToolImages(messages);

let tools;
if (Array.isArray(respReq.tools) && respReq.tools.length) {
tools = respReq.tools.filter(t => t && (t.type === 'function' || t.name)).map(t => ({
Expand Down Expand Up @@ -2918,6 +3031,9 @@ function createResponsesSseTranslator(model, responseId, created) {
inputTokens: 0,
outputTokens: 0,
cachedInputTokens: 0,
// 提前发 created/in_progress(不带内容):上游是 reasoning 模型,大 prompt 首字可能要十几秒,
// 这期间一个字节都不出网就会被中间层(实测 EdgeOne 源站 ~15s)或客户端首字节超时掐掉
start: startResponse,
get started() { return createdSent; },
get stopReason() { return finishReason; },
parseLine(line) {
Expand Down Expand Up @@ -2991,6 +3107,16 @@ function createResponsesSseTranslator(model, responseId, created) {

case 'error': {
this.upstreamError = mapCcEventError(event);
// 上游在 HTTP 200 之后于**流内**报错时,这里以前只赋值不打日志:客户端收到 400,
// 而 journalctl 里一片安静(本次排障就是靠 nginx 的 body_bytes_sent=0 反推的)。
// 对齐 /v1/chat/completions 路径的 CC stream error。
log('warn', 'CC stream error', {
path: '/v1/responses',
message: event.error?.message || event.message || 'Unknown error',
upstreamStatus: this.upstreamError.reportedStatus,
code: this.upstreamError.code,
mappedTo: this.upstreamError.status,
});
break;
}

Expand Down Expand Up @@ -3136,6 +3262,24 @@ async function handleResponses(req, res) {
await waitDrain(res);
};

// 上游已 200:立刻把响应头 + response.created / response.in_progress 推下去。
// 不能等首个内容事件 —— Codex 实测 reasoning_effort=max + 大 prompt,首字要 15s+,
// 这段时间此前**零字节出网**,于是 nginx access.log 全是 `499 0`(body_bytes_sent=0)、
// 中间 CDN(EdgeOne)按源站超时掐掉连接、客户端只能每 15 秒重试一次。
// created 是不带内容的协议首事件,先发符合 Responses 语义;上游随后失败会走 response.failed。
await writeEvents(translator.start());

// SSE 保活:对齐 /v1/messages 的心跳思路,但这里发**注释行**。
// Responses 协议没有 ping 事件,塞未知 event 类型有被严格解析器判错的风险;
// 注释行(以 ':' 开头)按 SSE 规范必须被忽略 —— chat 端点在静默事件时也是这么发的。
// 为什么必须发:首字前的静默期实测 15~40s,中间层的"源站空闲"超时(EdgeOne 实测约 15s)
// 会把连接掐掉 —— 现象是客户端 ~16s 断连、代理侧 Client disconnected、nginx 只记到很少字节。
const heartbeat = setInterval(() => {
// 回调是同步的,无法 await waitDrain,所以用 writableNeedDrain 直接跳过(背压时少一条注释无副作用)
if (aborted || !started || res.writableEnded || res.writableNeedDrain) return;
try { res.write(': keepalive\n\n'); } catch (e2) {}
}, 5000);

try {
while (true) {
const result = await Promise.race([reader.read(), idle.arm()]);
Expand Down Expand Up @@ -3214,6 +3358,7 @@ async function handleResponses(req, res) {
}
}
} finally {
clearInterval(heartbeat);
idle.dispose();
}

Expand Down
Loading