diff --git a/docs/architecture.ja.md b/docs/architecture.ja.md
index 1a65cf82d0..99a66f3a44 100644
--- a/docs/architecture.ja.md
+++ b/docs/architecture.ja.md
@@ -22,7 +22,7 @@
| モジュール | 一行説明 | ページ | ステータス |
|---|---|---|---|
| `storage` | 統合 SQLite: テーブルファミリー、kstate、チェックポイント、GC | [storage.md](./architecture/storage.md) · [zh](./architecture/storage.zh-CN.md) · [ja](./architecture/storage.ja.md) | ✅ |
-| `pipeline` | リクエストパイプライン(handle / prepare-* / relay / inject) | [pipeline.md](./architecture/pipeline.md) · [zh](./architecture/pipeline.zh-CN.md) · [ja](./architecture/pipeline.ja.md) | ✅ |
+| `pipeline` | リクエストパイプライン(終端コンテンツ拒否/usage) | [pipeline.md](./architecture/pipeline.md) · [zh](./architecture/pipeline.zh-CN.md) · [ja](./architecture/pipeline.ja.md) | ✅ |
| `lanes` | ホストレーン(dsh / pi / opencode / codex / ベアプロキシ + lane-decisions) | [lanes.md](./architecture/lanes.md) · [zh](./architecture/lanes.zh-CN.md) · [ja](./architecture/lanes.ja.md) | ✅ |
| `kernel` | 圧縮エンジン(acp-kernel: フォールド、サマリー、リファレンス台帳) | [kernel.md](./architecture/kernel.md) · [zh](./architecture/kernel.zh-CN.md) · [ja](./architecture/kernel.ja.md) | ✅ |
| `identity` | セッションおよびメッセージのアイデンティティ(セッション ID、ペルソナフォーク、msgid チャネル) | [identity.md](./architecture/identity.md) · [zh](./architecture/identity.zh-CN.md) · [ja](./architecture/identity.ja.md) | ✅ |
diff --git a/docs/architecture.md b/docs/architecture.md
index 6097ab54c6..38880d1a1b 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -22,7 +22,7 @@ How to read it:
| Module | One line | Pages | Status |
|---|---|---|---|
| `storage` | Unified SQLite: table family, kstate, checkpoints, GC | [storage.md](./architecture/storage.md) · [zh](./architecture/storage.zh-CN.md) · [ja](./architecture/storage.ja.md) | ✅ |
-| `pipeline` | Request pipeline (handle / prepare-* / relay / inject) | [pipeline.md](./architecture/pipeline.md) · [zh](./architecture/pipeline.zh-CN.md) · [ja](./architecture/pipeline.ja.md) | ✅ |
+| `pipeline` | Request pipeline (handle / prepare-* / relay / inject; terminal content rejection / usage) | [pipeline.md](./architecture/pipeline.md) · [zh](./architecture/pipeline.zh-CN.md) · [ja](./architecture/pipeline.ja.md) | ✅ |
| `lanes` | Host lanes (dsh / pi / opencode / codex / bare proxy + lane-decisions; Pi Anthropic full-request compatibility) | [lanes.md](./architecture/lanes.md) · [zh](./architecture/lanes.zh-CN.md) · [ja](./architecture/lanes.ja.md) | ✅ |
| `kernel` | Compression engine (acp-kernel: folds, summaries, ref ledger) | [kernel.md](./architecture/kernel.md) · [zh](./architecture/kernel.zh-CN.md) · [ja](./architecture/kernel.ja.md) | ✅ |
| `identity` | Session & message identity (session id, persona fork, msgid channels) | [identity.md](./architecture/identity.md) · [zh](./architecture/identity.zh-CN.md) · [ja](./architecture/identity.ja.md) | ✅ |
diff --git a/docs/architecture.zh-CN.md b/docs/architecture.zh-CN.md
index 57f0913366..33b453f31b 100644
--- a/docs/architecture.zh-CN.md
+++ b/docs/architecture.zh-CN.md
@@ -22,7 +22,7 @@
| 模块 | 一句话 | 页面 | 状态 |
|---|---|---|---|
| `storage` | 统一 SQLite 存储(表族 / kstate / ckpt / GC) | [storage.zh-CN.md](./architecture/storage.zh-CN.md) · [EN](./architecture/storage.md) | ✅ |
-| `pipeline` | 请求管道(handle / prepare-* / relay / inject) | [pipeline.zh-CN.md](./architecture/pipeline.zh-CN.md) · [EN](./architecture/pipeline.md) | ✅ |
+| `pipeline` | 请求管道(handle / prepare-* / relay / inject;终止性内容拒绝/用量结算) | [pipeline.zh-CN.md](./architecture/pipeline.zh-CN.md) · [EN](./architecture/pipeline.md) | ✅ |
| `lanes` | 宿主车道(dsh / pi / opencode / codex / 裸代理 + lane-decisions;Pi Anthropic 全量请求兼容) | [lanes.zh-CN.md](./architecture/lanes.zh-CN.md) · [EN](./architecture/lanes.md) | ✅ |
| `kernel` | 压缩内核(acp-kernel:折叠 / 摘要 / ref 账本) | [kernel.zh-CN.md](./architecture/kernel.zh-CN.md) · [EN](./architecture/kernel.md) | ✅ |
| `identity` | 会话与消息身份(session id / persona fork / msgid 通道) | [identity.zh-CN.md](./architecture/identity.zh-CN.md) · [EN](./architecture/identity.md) | ✅ |
diff --git a/docs/architecture/assets/pipeline.en.png b/docs/architecture/assets/pipeline.en.png
index 89c087a8cf..af30e05aa9 100644
Binary files a/docs/architecture/assets/pipeline.en.png and b/docs/architecture/assets/pipeline.en.png differ
diff --git a/docs/architecture/assets/pipeline.en.svg b/docs/architecture/assets/pipeline.en.svg
index b1e34c6057..b430d403bb 100644
--- a/docs/architecture/assets/pipeline.en.svg
+++ b/docs/architecture/assets/pipeline.en.svg
@@ -1,5 +1,5 @@
\ No newline at end of file
+Module: request pipeline (src/server + src/loop)one HTTP request, from inbound bytes to outbound stream — every wire, both compression modesInboundclient bytesmarker strip (src/marker/):ordered pipeline, 4 wiresroute triage: /__bili/* vs model APIprepare-* (per-wire)anthropic / openai /responses / googlefold → rebuild → injectsystem + nudge placementacp-kernel(zero changes)fold decision projectUnitblocks / refs / dead_refssummary + nudge flat 50Ksrc/loop (unified)protocol-neutral core4 wire adapterstool adjudicationtag-echo-filter: prose only,tool args byte-exactupstreamPreflight & gatespreflight.ts: hold grace, dead-end cooldownreasoning-guard: signed payloads never foldedrequest-body-budget: receive/decode/send byte capscontent-encoding: decompression-bomb guard (413)Error & recoveryexplicit content rejection → stopkeep diagnostics + request IDsno key / thinking / overflow probessettle already reported usageEgress rewrite (stream-*)SSE per-wire (openai/responses/google)cache-control breakpoints (#1637)pf-*/envelope headers never leave (hop list)wire-body: trailing-user-turn appendTwo compression modes run through the SAME pipeline (KDD #7): plugin lane — agent owns compress, carrier is the tool call; proxy mode — proxy runs compress, carrier is the acp_summary re-voiced as user.Hard rule: thinking-family blocks are signature-verified, NEVER rewritten (#1960); tool-call arguments are user intent, forwarded byte-exact (#1039).other errors keep their recoveryexplicit legacy completion kept
\ No newline at end of file
diff --git a/docs/architecture/assets/pipeline.zh-CN.png b/docs/architecture/assets/pipeline.zh-CN.png
index 9b0256dd9d..d9c782c009 100644
Binary files a/docs/architecture/assets/pipeline.zh-CN.png and b/docs/architecture/assets/pipeline.zh-CN.png differ
diff --git a/docs/architecture/assets/pipeline.zh-CN.svg b/docs/architecture/assets/pipeline.zh-CN.svg
index 7cde0d28c8..3094c5c457 100644
--- a/docs/architecture/assets/pipeline.zh-CN.svg
+++ b/docs/architecture/assets/pipeline.zh-CN.svg
@@ -1,5 +1,5 @@
\ No newline at end of file
+模块:请求管道(src/server + src/loop)一次 HTTP 请求,从入站字节到出站流 —— 四种 wire、两种压缩模式入站客户端字节marker strip(src/marker/):有序管道、四种 wire路由分诊:/__bili/* 还是模型 APIprepare-*(按 wire)anthropic / openai /responses / google折叠 → 重建 → 注入system + nudge 落位acp-kernel(零改动)折叠判定 projectUnitblocks / refs / dead_refs摘要 + nudge flat 50Ksrc/loop(统一)协议中立核心4 个 wire 适配器工具裁决tag-echo-filter:只滤散文、工具参数逐字节上游预检与闸门preflight.ts:hold 宽限、死路冷却reasoning-guard:签名载荷永不折叠request-body-budget:收/解/发字节预算content-encoding:解压炸弹守卫(413)错误与恢复明确内容拒绝 → 终止本次请求保留诊断与请求 ID不探测缓存键/去 thinking/缩窗结算已经报告的 usage出站改写(stream-*)SSE 按 wire(openai/responses/google)cache-control 断点(#1637)pf-*/信封头永不出代理(hop 白名单)wire-body:尾 user 回合补位两种压缩模式走同一条管道(KDD #7):plugin 车道——agent 自己压、载体是 tool call;proxy 模式——代理压、载体是 acp_summary 改口为 user。硬规则:thinking 族块签名验证、永不改写(#1960);tool-call 参数是用户意图,逐字节转发(#1039)。其他错误保留对应恢复路径显式 legacy completion 兼容保留
\ No newline at end of file
diff --git a/docs/architecture/pipeline.ja.md b/docs/architecture/pipeline.ja.md
index f35ddce2aa..bd0d1a353d 100644
--- a/docs/architecture/pipeline.ja.md
+++ b/docs/architecture/pipeline.ja.md
@@ -1,6 +1,6 @@
# モジュール: リクエストパイプライン (`src/server` + `src/loop`)
-> [アーキテクチャハブ](../architecture.ja.md) の一部 · 中国語版: [pipeline.zh-CN.md](./pipeline.zh-CN.md) · 2026-11-10 時点, master
+> [アーキテクチャハブ](../architecture.ja.md) の一部 · 中国語版: [pipeline.zh-CN.md](./pipeline.zh-CN.md) · 2026-11-15 時点, candidate

(ビットマップフォールバック: [pipeline.en.png](./assets/pipeline.en.png))
@@ -29,6 +29,8 @@
**ゲートとリカバリ。** `preflight.ts` (ホールドグレース、デッドエンドクールダウン)、`reasoning-guard` (署名済みペイロードは決してフォールド入力にならない)、`request-body-budget` (受信/デコード/送信バイト上限、パフォーマンスより可用性 #3128)、`content-encoding` (デコンプレッションボムガード、413)。エラー形状: `stream-error` (最小限の SSE エラー + 終了)、`fake-completion` (オプトインのリトライヒント)、`degenerate-turn` / `degenerate-retry`、および `exit-matrix` (ワイヤー終了 × 懸念事項、#588)。
+**明示的なコンテンツ拒否。** HTTP 400 の code が `content-blocked`、または type が `agent_router_content_blocked` なら、一般的な再送、キャッシュキー探査、thinking 削除、overflow 回復を停止する。回復ループは元の試行の usage を記録してから拒否を返す。Anthropic の EOF は既知の部分 usage を保持するが、完了とは扱わない。ネイティブエラーは本文・`x-request-id` / `request-id` ヘッダーの診断 ID を保持する。Responses は `error.code`、Google は 400 / `INVALID_ARGUMENT` を使う。明示的な `streamErrorShape="completion"` の互換動作は維持する。未知の 400 や実際の schema/キャッシュ/context エラー、一時的障害は従来の回復経路を使う。`WC-026` の fake は観測された判決のみを再現する。
+
## 主要エントリ
`src/server/handle.ts` (トリアージ) · `src/server/prepare-*.ts` (ワイヤーごとのリクエスト準備) · `src/marker/` (受信タグストリップ) · `src/loop/` (統一コア + アダプタ) · `src/server/stream-*.ts` (ワイヤーごとの送信) · `src/egress-transforms.ts` (ユーザー送信ボディ書き換えプラグイン、#6003) · `src/server/preflight.ts` · `src/server/exit-matrix.ts`
diff --git a/docs/architecture/pipeline.md b/docs/architecture/pipeline.md
index 19da595a52..e889b0cec8 100644
--- a/docs/architecture/pipeline.md
+++ b/docs/architecture/pipeline.md
@@ -1,6 +1,6 @@
# Module: request pipeline (`src/server` + `src/loop`)
-> Part of the [architecture hub](../architecture.md) · 中文: [pipeline.zh-CN.md](./pipeline.zh-CN.md) · as of 2026-11-10, master
+> Part of the [architecture hub](../architecture.md) · 中文: [pipeline.zh-CN.md](./pipeline.zh-CN.md) · as of 2026-11-15, candidate

(bitmap fallback: [pipeline.en.png](./assets/pipeline.en.png))
@@ -29,6 +29,8 @@ Every model-traffic request that reaches the proxy passes through this module: i
**Gates & recovery.** `preflight.ts` (hold grace, dead-end cooldown), `reasoning-guard` (signed payloads are never fold inputs), `request-body-budget` (receive/decode/send byte caps, availability over performance #3128), `content-encoding` (decompression-bomb guard, 413). Error shapes: `stream-error` (minimal SSE error + finish), `fake-completion` (opt-in retry hint), `degenerate-turn` / `degenerate-retry`, and `exit-matrix` (wire-exit × concerns, #588).
+**Explicit content rejection.** HTTP 400 with error code `content-blocked` or type `agent_router_content_blocked` stops generic replay, cache-key probes, thinking removal and overflow recovery. Recovery loops forward the rejection instead of an empty successful completion, after settling the original attempt's reported usage. Anthropic EOF retains partial usage without claiming completion. Native error frames retain diagnostics and available request IDs from the body or `x-request-id` / `request-id` headers. Responses maps the identity to `error.code`; Google uses 400 / `INVALID_ARGUMENT`. Existing explicit `streamErrorShape="completion"` compatibility rendering remains. Unknown 400, genuine schema/cache/context errors and transient failures keep their recovery paths. `WC-026` records the observed envelope; its fake scripts a verdict without inventing a content policy.
+
## Key entries
`src/server/handle.ts` (triage) · `src/server/prepare-*.ts` (per-wire request prep) · `src/marker/` (inbound tag strip) · `src/loop/` (unified core + adapters) · `src/server/stream-*.ts` (per-wire egress) · `src/egress-transforms.ts` (user egress body-rewrite plugins, #6003) · `src/server/preflight.ts` · `src/server/exit-matrix.ts`
diff --git a/docs/architecture/pipeline.zh-CN.md b/docs/architecture/pipeline.zh-CN.md
index c17d539139..48d2a2e251 100644
--- a/docs/architecture/pipeline.zh-CN.md
+++ b/docs/architecture/pipeline.zh-CN.md
@@ -1,6 +1,6 @@
# 模块:请求管道(`src/server` + `src/loop`)
-> [架构总览](../architecture.zh-CN.md) 的一个模块 · English: [pipeline.md](./pipeline.md) · 截至 2026-11-10,master
+> [架构总览](../architecture.zh-CN.md) 的一个模块 · English: [pipeline.md](./pipeline.md) · 截至 2026-11-15,candidate

(位图备选:[pipeline.zh-CN.png](./assets/pipeline.zh-CN.png))
@@ -29,6 +29,8 @@
**闸门与恢复。** `preflight.ts`(hold 宽限、死路冷却)、`reasoning-guard`(签名载荷永不进折叠输入)、`request-body-budget`(收/解/发字节预算,可用性大于性能 #3128)、`content-encoding`(解压炸弹守卫,413)。错误形态:`stream-error`(最小 SSE 错误+收尾)、`fake-completion`(可选重试提示)、`degenerate-turn` / `degenerate-retry`、`exit-matrix`(wire 出口 × 关注点,#588)。
+**明确的内容拒绝。** HTTP 400 的 error code 为 `content-blocked` 或 type 为 `agent_router_content_blocked` 时,停止通用重发、缓存键探测、去掉 thinking 重试和溢出恢复。恢复分支结算原轮已报告的 usage 后传递拒绝,不输出空的成功结束;Anthropic EOF 保留部分 usage,但不宣称完成。原生错误帧保留诊断及正文或 `x-request-id` / `request-id` 响应头中可用的请求 ID;Responses 将标识放入 `error.code`,Google 使用 400 / `INVALID_ARGUMENT`。已有显式 `streamErrorShape="completion"` 兼容渲染保持原语义。未知 400、真正的 schema/缓存/上下文错误和暂时性故障继续各自恢复路径。`WC-026` 登记已观察到的错误封装;fake 只模拟判决,不臆造内容检测规则。
+
## 关键入口
`src/server/handle.ts`(分诊) · `src/server/prepare-*.ts`(按 wire 请求准备) · `src/marker/`(入站剥标签) · `src/loop/`(统一核心+适配器) · `src/server/stream-*.ts`(按 wire 出站) · `src/egress-transforms.ts`(用户出站体改写插件,#6003) · `src/server/preflight.ts` · `src/server/exit-matrix.ts`
diff --git a/reference/architecture.md b/reference/architecture.md
index 6fb6f6adef..8aa2cbbe63 100644
--- a/reference/architecture.md
+++ b/reference/architecture.md
@@ -27,7 +27,7 @@ billion-context/
│ │ ├── prepare-google.ts # Gemini request preparation incl. :countTokens twin (#1440)
│ │ ├── prepare-openai.ts # OpenAI chat request preparation (#1440)
│ │ ├── prepare-responses.ts # Responses request preparation + codex compact/prompt-cache helpers (#1440)
-│ │ ├── relay.ts # Upstream relay zone: forward() + fake-completion recovery (#1440 P2 cut 4)
+│ │ ├── relay.ts # Upstream relay; classified recovery excludes terminal content rejection
│ │ ├── rejection-diagnostics.ts # Bounded terminal-cause diagnostic for a relayed upstream rejection: one nested attempts[].details.error.message, scrubbed + bounded, appended to the relay log line (#4452)
│ │ ├── request-cost.ts # Per-request local-cost line (outbound measured at the real wire body) + #5408 heartbeat + wall-clock slow-session advisory, facts only (#903/#4528/#5744)
│ │ ├── responses-ordering.ts # #564 Responses assistant-run ordering repair + producer-owned turn-separator provenance (#2627)
@@ -95,6 +95,7 @@ billion-context/
│ ├── absorb.ts # absorb tool (kernel ACP_TOOL_NAMES extension)
│ ├── compress-loop-anthropic.ts # Non-stream Anthropic proxy-tool loop (#5957)
│ ├── compress-loop-responses.ts # Compress loop for Responses API format
+│ ├── responses-system-sections.ts # Shared Responses developer-section join for steady + proxy-loop rebuild paths (#6922)
│ ├── compress-settings.ts # Three-level compress config merge (global→provider→model)
│ ├── chat-pack.ts # Bundled chat prompt pack: relationship-first compress philosophy (#5319)
│ ├── compress-tool.ts # ACP tool surface — thin re-export from acp-kernel
@@ -361,7 +362,7 @@ billion-context/
When navigating this codebase, these are the load-bearing entry points:
- **Request pipeline** — `src/server.ts` is the single HTTP entry; everything flows through `createServer()` → route matching → `forward()`. The file is large by design (one pipeline, many wire shapes).
-- **Loop core** — `src/loop/core.ts` owns the protocol-neutral event model and all tool-call adjudication. Wire adapters (`adapter-*.ts`) translate between wire events and the core's event vocabulary.
+- **Loop core** — `src/loop/core.ts` owns the protocol-neutral event model and all tool-call adjudication. Wire adapters (`adapter-*.ts`) translate between wire events and the core's event vocabulary. Terminal content rejections retain diagnostics and request IDs across tool and recovery continuations; measured attempts settle before recovery exits.
- **Knobs** — every behavior knob resolves through `src/knobs.ts` (env > config file > default, #2030). Never add a new `process.env` read in a leaf module — see AGENTS.md "Environment Variable Discipline".
- **Update path** — `src/update.ts` is deliberately self-contained and conservative; it installs via tarball extraction (not `npm install`) to avoid lifecycle-script surprises on user machines. It is load-bearing infrastructure: changes require a no-op validation release first (§5).
- **Agent plugins** — `src/agent/*.ts` are thin host-specific adapters; shared logic lives in `src/agent/shared.ts`. Each host has a `-native.ts` bootstrap gate variant.
diff --git a/src/fetch-util.ts b/src/fetch-util.ts
index 005d4e50fc..3cd5092cc1 100644
--- a/src/fetch-util.ts
+++ b/src/fetch-util.ts
@@ -10,6 +10,7 @@ import {
maxShrinkPerCompress as knobMaxShrinkPerCompress,
} from "./knobs.js";
import { log } from "./logger.js";
+import { parseContentRejection } from "./util.js";
/** HTTP robustness helpers for the proxy.
@@ -379,12 +380,14 @@ export class UpstreamHttpError extends Error {
readonly status: number;
readonly body: string;
readonly attempts: number;
- constructor(status: number, body: string, attempts: number) {
+ readonly requestId?: string;
+ constructor(status: number, body: string, attempts: number, requestId?: string) {
super(`upstream error ${status}`);
this.name = "UpstreamHttpError";
this.status = status;
this.body = body;
this.attempts = attempts;
+ this.requestId = requestId;
}
}
@@ -420,6 +423,7 @@ const DECLARATION_NODE_BUDGET = 4_096;
export function isTransientUpstreamError(status: number, body: string): boolean {
if (status === 429 || status >= 500) return true;
if (status < 400) return false;
+ if (parseContentRejection(status, body)) return false;
const lower = body.toLowerCase();
if (TRANSIENT_BODY_MARKERS.some((marker) => lower.includes(marker))) return true;
return bodyDeclaresRetryable(body);
@@ -575,7 +579,8 @@ export async function fetchWithRetry(
await sleep(delayMs, externalSignal);
continue;
}
- throw new UpstreamHttpError(result.response.status, errText, attempt);
+ throw new UpstreamHttpError(result.response.status, errText, attempt,
+ result.response.headers.get("x-request-id") ?? result.response.headers.get("request-id") ?? undefined);
}
}
diff --git a/src/loop/adapter-anthropic.ts b/src/loop/adapter-anthropic.ts
index 468f08e675..efa64f5a92 100644
--- a/src/loop/adapter-anthropic.ts
+++ b/src/loop/adapter-anthropic.ts
@@ -426,6 +426,7 @@ export function createAnthropicAdapter(requestBody: Record, ori
}
const u = (msg.usage ?? {}) as Record;
if (typeof u.input_tokens === "number") roundInput = u.input_tokens;
+ if (typeof u.output_tokens === "number") roundOutput = u.output_tokens;
if (typeof u.cache_read_input_tokens === "number") roundCached = u.cache_read_input_tokens;
if (typeof u.cache_creation_input_tokens === "number") roundCreation = u.cache_creation_input_tokens;
// #4128: an anthropic-wire relay stamps billing_usage on the start frame.
@@ -767,6 +768,20 @@ export function createAnthropicAdapter(requestBody: Record, ori
yield { kind: "meta", chunk: rawBuf, firstRoundOnly: true } as ParsedStreamEvent;
}
}
+ // EOF can precede the terminal frames. Preserve any usage already reported
+ // by message_start so a failed continuation still settles the original
+ // attempt. This is a partial measurement, not a successful completion.
+ if (!usageYielded && (roundInput !== undefined || roundCached !== undefined || roundCreation !== undefined || roundOutput !== undefined)) {
+ yield {
+ kind: "usage",
+ inputTokens: roundInput,
+ outputTokens: roundOutput,
+ cachedTokens: roundCached,
+ creationTokens: roundCreation,
+ declaredInclusive: roundDeclaredInclusive,
+ cacheCreation: roundCacheCreation,
+ } as ParsedStreamEvent;
+ }
},
emitText(delta) {
@@ -816,7 +831,7 @@ export function createAnthropicAdapter(requestBody: Record, ori
return [...threadResponseIds];
},
- emitError(message) {
+ emitError(message, rejection) {
const parts: Buffer[] = [];
if (!messageStartForwarded) {
parts.push(buildSyntheticMessageStart());
@@ -838,7 +853,7 @@ export function createAnthropicAdapter(requestBody: Record, ori
parts.push(buildTerminal("end_turn", 0, 0, 0));
} else {
parts.push(Buffer.from(
- `event: error\ndata: ${JSON.stringify({ type: "error", error: { type: "server_error", code: "upstream_error", message: `[acp-proxy: ${message}]` } })}\n\n`,
+ `event: error\ndata: ${JSON.stringify({ type: "error", error: { type: rejection?.type ?? rejection?.code ?? "server_error", code: rejection?.code ?? rejection?.type ?? "upstream_error", message: rejection ? message : `[acp-proxy: ${message}]` } })}\n\n`,
"utf8",
));
}
diff --git a/src/loop/adapter-commandcode.ts b/src/loop/adapter-commandcode.ts
index ff16644df3..6204c91465 100644
--- a/src/loop/adapter-commandcode.ts
+++ b/src/loop/adapter-commandcode.ts
@@ -263,8 +263,8 @@ export function createCommandcodeAdapter(
return lineBuf(JSON.stringify({ type: "finish", finishReason: opts?.finishReason ?? "stop", totalUsage }));
},
- emitError(message: string): Buffer {
- return lineBuf(JSON.stringify({ type: "error", error: "acp_proxy_error", message }));
+ emitError(message, rejection): Buffer {
+ return lineBuf(JSON.stringify({ type: "error", error: rejection?.code ?? rejection?.type ?? "acp_proxy_error", message }));
},
};
}
diff --git a/src/loop/adapter-google.ts b/src/loop/adapter-google.ts
index 149c7c815f..98673ceae3 100644
--- a/src/loop/adapter-google.ts
+++ b/src/loop/adapter-google.ts
@@ -1000,8 +1000,8 @@ export function createGoogleAdapter(
return buildChunk([], { candidate: { finishReason: googleFinishReason(opts?.finishReason) }, top: usage });
},
- emitError(message) {
- return sseFrame({ error: { code: 500, message, status: "INTERNAL" } });
+ emitError(message, rejection) {
+ return sseFrame({ error: { code: rejection ? 400 : 500, message, status: rejection ? "INVALID_ARGUMENT" : "INTERNAL" } });
},
};
}
diff --git a/src/loop/adapter-openai.ts b/src/loop/adapter-openai.ts
index 50afc60eef..df4f4bc35d 100644
--- a/src/loop/adapter-openai.ts
+++ b/src/loop/adapter-openai.ts
@@ -767,7 +767,7 @@ export function createOpenaiAdapter(requestBody: Record, client
return Buffer.concat([buildFinish(finishReason, usage), Buffer.from("data: [DONE]\n\n", "utf8")]);
},
- emitError(message) {
+ emitError(message, rejection) {
// #1455: present the failure AS a failure (see the anthropic twin). The
// legacy shape — error text + finish_reason "stop" + [DONE] — read as a
// normal completion to clients and suppressed their retry logic. The
@@ -782,7 +782,7 @@ export function createOpenaiAdapter(requestBody: Record, client
]);
}
return Buffer.concat([
- Buffer.from(`data: ${JSON.stringify({ error: { type: "server_error", code: "upstream_error", message: `[acp-proxy: ${message}]` } })}\n\n`, "utf8"),
+ Buffer.from(`data: ${JSON.stringify({ error: { type: rejection?.type ?? rejection?.code ?? "server_error", code: rejection?.code ?? rejection?.type ?? "upstream_error", message: rejection ? message : `[acp-proxy: ${message}]` } })}\n\n`, "utf8"),
Buffer.from("data: [DONE]\n\n", "utf8"),
]);
},
diff --git a/src/loop/adapter-responses.ts b/src/loop/adapter-responses.ts
index eda5d21d50..7e872b4ce7 100644
--- a/src/loop/adapter-responses.ts
+++ b/src/loop/adapter-responses.ts
@@ -811,14 +811,14 @@ export function createResponsesAdapter(textProtocol?: boolean, projection?: Resp
return buildCompleted(resp);
},
- emitError(message) {
+ emitError(message, rejection) {
const parts: Buffer[] = [];
const created = ensureCreated();
if (created) parts.push(created);
const resp = {
id: createdRespId ?? `resp-error-${Date.now()}`,
status: "failed",
- error: { code: "server_error", message },
+ error: { code: rejection?.code ?? rejection?.type ?? "server_error", message },
};
parts.push(Buffer.from(
`event: response.failed\ndata: ${JSON.stringify({ type: "response.failed", response: resp })}\n\n`,
diff --git a/src/loop/core.ts b/src/loop/core.ts
index 269bb7a600..3aa41d78bc 100644
--- a/src/loop/core.ts
+++ b/src/loop/core.ts
@@ -46,7 +46,7 @@ import { bodyDumpEnabled as knobBodyDumpEnabled, imageRescaleMaxDim } from "../k
import { dumpsDir } from "../paths.js";
import { isStrictReasoningEcho, modelIdOf, normalizeStrictEchoBody } from "../strict-echo.js";
import { log as loggerLog } from "../logger.js";
-import { promptInputTotal, type WireProtocol } from "../util.js";
+import { parseContentRejection, promptInputTotal, type ContentRejection, type WireProtocol } from "../util.js";
import { DEGENERATE_RETRY_NUDGE } from "../degenerate-retry.js";
import { endsWithAnnouncement, endsWithDraftClose, lastUserSummaryInstruction, requestExpectsProseSummary } from "../degenerate-turn.js";
import { safePrefix, safeSuffix, scrubLoneSurrogateEscapesOnJson } from "../text-safe.js";
@@ -432,7 +432,7 @@ export interface CompressLoopAdapter {
emitToolCall(call: ToolCallEmit): Buffer;
emitMarker(toolName: string, result: string): Buffer;
emitCompletion(opts?: EmitCompletionOpts): Buffer;
- emitError(message: string): Buffer;
+ emitError(message: string, rejection?: ContentRejection): Buffer;
extractTextTriggers?(text: string): ExtractedTextTriggers;
// #2701 (anthropic Threads only): the id of the LATEST upstream response
// observed on the wire — the thread tail a re-request must continue from.
@@ -922,11 +922,11 @@ export async function* runCompressLoop(
// recordUsage below runs once per ROUND, but a successful retry re-fetches within
// the same round and the top-of-loop `usage = {}` reset drops the replaced attempt's
// usage before it is ever recorded — billed tokens vanish from the internal ledger.
- // Called on the success path only: each upstream attempt is accounted exactly once.
- // A FAILED retry never reaches these call sites (it catches and falls through to
- // break), so the surviving original attempt is settled once by recordUsage — no
- // double counting. The client-facing completion still carries only the FINAL
- // attempt's usage (emitCompletion reads `usage`, which this never mutates), so the
+ // Settle before a successful retry replaces this attempt, or a terminal rejection
+ // returns before the round-level settlement. Other failed retries fall through
+ // to recordUsage below. Each branch records only the measured original attempt,
+ // never usage for an HTTP rejection. The client-facing completion still carries
+ // only the FINAL attempt's usage (emitCompletion reads `usage`, unchanged here), so the
// internal ledger and the response's usage representation stay separate.
const settleAttemptUsage = (): void => {
if (
@@ -1166,6 +1166,13 @@ export async function* runCompressLoop(
settleAttemptUsage();
continue;
} catch (e) {
+ const rejection = e instanceof UpstreamHttpError ? parseContentRejection(e.status, e.body, e.requestId) : null;
+ if (rejection) {
+ settleAttemptUsage();
+ ctx.log("[acp-loop] recovery rejected for content; ending the turn with the original diagnostic");
+ yield adapter.emitError(rejection.message, rejection);
+ return;
+ }
if (e instanceof UpstreamHttpError) {
const suffix = e.attempts > 1 ? ` after ${e.attempts} attempt(s)` : "";
ctx.log(`[acp-loop] round ${round}: truncation retry failed (upstream error ${e.status}${suffix}: ${e.body.slice(0, 200)})`);
@@ -1232,6 +1239,13 @@ export async function* runCompressLoop(
settleAttemptUsage();
continue;
} catch (e) {
+ const rejection = e instanceof UpstreamHttpError ? parseContentRejection(e.status, e.body, e.requestId) : null;
+ if (rejection) {
+ settleAttemptUsage();
+ ctx.log("[acp-loop] recovery rejected for content; ending the turn with the original diagnostic");
+ yield adapter.emitError(rejection.message, rejection);
+ return;
+ }
if (e instanceof UpstreamHttpError) {
ctx.log(`[acp-loop] round ${round}: continuation retry failed (upstream error ${e.status}: ${e.body.slice(0, 200)}); falling back to the truncation error`);
} else {
@@ -1281,6 +1295,13 @@ export async function* runCompressLoop(
settleAttemptUsage();
continue;
} catch (e) {
+ const rejection = e instanceof UpstreamHttpError ? parseContentRejection(e.status, e.body, e.requestId) : null;
+ if (rejection) {
+ settleAttemptUsage();
+ ctx.log("[acp-loop] recovery rejected for content; ending the turn with the original diagnostic");
+ yield adapter.emitError(rejection.message, rejection);
+ return;
+ }
if (e instanceof UpstreamHttpError) {
ctx.log(`[acp-loop] round ${round}: degenerate retry failed (upstream error ${e.status}: ${e.body.slice(0, 200)}); passing the empty turn through`);
} else {
@@ -1362,6 +1383,13 @@ export async function* runCompressLoop(
settleAttemptUsage();
continue;
} catch (e) {
+ const rejection = e instanceof UpstreamHttpError ? parseContentRejection(e.status, e.body, e.requestId) : null;
+ if (rejection) {
+ settleAttemptUsage();
+ ctx.log("[acp-loop] recovery rejected for content; ending the turn with the original diagnostic");
+ yield adapter.emitError(rejection.message, rejection);
+ return;
+ }
if (e instanceof UpstreamHttpError) {
ctx.log(`[acp-loop] round ${round}: stalled-tail retry failed (upstream error ${e.status}: ${e.body.slice(0, 200)}); passing the turn through`);
} else {
@@ -1852,6 +1880,7 @@ export async function* runCompressLoop(
e.status < 400 ||
e.status >= 500 ||
degradedRetried ||
+ parseContentRejection(e.status, e.body, e.requestId) !== null ||
isThinkingModifiedError(e) ||
isReasoningRequiredError(e) ||
(ctx.protocol !== "anthropic" && ctx.protocol !== "google") ||
@@ -1908,6 +1937,7 @@ export async function* runCompressLoop(
// #5495: DeepSeek's Anthropic-wire endpoint spells it content[].thinking.
if (
e.status === 400 &&
+ parseContentRejection(e.status, e.body, e.requestId) === null &&
/reasoning_(?:content|text)|content\[\]\.thinking/i.test(e.body) &&
ctx.session.metadata.strictReasoningEcho !== true
) {
@@ -1922,7 +1952,8 @@ export async function* runCompressLoop(
const suffix = e.attempts > 1 ? ` after ${e.attempts} attempt(s)` : "";
ctx.log(`[acp-proxy: compress loop upstream error ${e.status}${suffix}: ${e.body.slice(0, 200)}]`);
loggerLog("error", `[acp-loop] upstream error ${e.status}${suffix}: ${e.body.slice(0, 200)}`);
- yield adapter.emitError(`upstream error ${e.status}${suffix}: ${e.body.slice(0, 200)}`);
+ const rejection = parseContentRejection(e.status, e.body, e.requestId);
+ yield adapter.emitError(rejection?.message ?? `upstream error ${e.status}${suffix}: ${e.body.slice(0, 200)}`, rejection ?? undefined);
return;
}
diff --git a/src/server/relay.ts b/src/server/relay.ts
index 29fa2581a4..2b63a91f0e 100644
--- a/src/server/relay.ts
+++ b/src/server/relay.ts
@@ -65,7 +65,7 @@ import { clearUpstreamAlertsForHost, noteCircuitFailFastLog, recordUpstreamAlert
import { describeUpstreamFailure, formatUpstreamError, proxyDispatcher, recordUpstreamConnection } from "../upstream-proxy.js";
import { markExpectedFailFast, withUpstreamFailure, type UpstreamFailureKind } from "../upstream-fail.js";
import { noteUpstreamThrottle429, noteUpstreamThrottleResolved, releaseUpstreamThrottleProbe, requestModelFromBody, throttle429ModelScope, type ThrottleLocalReject, upstreamThrottleGate, upstreamThrottlePeekReject } from "../upstream-throttle.js";
-import { applyEstimateCalibration, BILI_HOST_RECOVERY_OWNER_HEADER, BILI_HOST_RECOVERY_OWNER_OMP, currentCalibrationFactor, inspectContextOverflow, isMarkerlessOverflowReject, MIN_ASSUMED_WINDOW_TOKENS, normalizeUpstreamOrigin, usageOutputTotal, usageTotals, type ContextOverflowInfo, type WireProtocol } from "../util.js";
+import { applyEstimateCalibration, BILI_HOST_RECOVERY_OWNER_HEADER, BILI_HOST_RECOVERY_OWNER_OMP, currentCalibrationFactor, inspectContextOverflow, parseContentRejection, isMarkerlessOverflowReject, MIN_ASSUMED_WINDOW_TOKENS, normalizeUpstreamOrigin, usageOutputTotal, usageTotals, type ContextOverflowInfo, type WireProtocol } from "../util.js";
import { billOutputUsage } from "../billing.js";
import { DUMP_PLAINTEXT_BANNER } from "../dump-banner.js";
import { recordPckAblation } from "../pck-probe.js";
@@ -1409,7 +1409,8 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
// auto-retry with the offending role rewritten to "system". On success the
// mapping is remembered on the session (never written to config — the log
// carries the permanent per-provider snippet instead). On failure the
- // original response continues downstream verbatim. Error bodies for these
+ // original response continues downstream verbatim unless the retry returns
+ // an explicit terminal content verdict. Error bodies for these
// request-validation statuses are small (buffered below).
if (
compatProtocol &&
@@ -1436,7 +1437,8 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
clearTimer: upstreamResult.clearTimer,
stopIdleTimer: upstreamResult.stopIdleTimer,
};
- const namedRejection = detectRoleRejection(upstreamResult.response.status, roleErrText);
+ const contentRejected = parseContentRejection(upstreamResult.response.status, roleErrText) !== null;
+ const namedRejection = contentRejected ? null : detectRoleRejection(upstreamResult.response.status, roleErrText);
// #1996: placement-only rejections name no role (vLLM+Qwen
// chat_template: "System message must be at the beginning.") — enter
// the ladder when the error matches a placement marker AND the wire
@@ -1444,7 +1446,7 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
// system item (plugin-mode #1638 verbatim pass-through) gets the same
// single-hop repair instead of a permanent 400 loop on every retry.
const rejection = namedRejection ??
- (detectSystemPlacementError(upstreamResult.response.status, roleErrText) &&
+ (!contentRejected && detectSystemPlacementError(upstreamResult.response.status, roleErrText) &&
hasOffHeadSystem(wireBody, compatProtocol)
? { role: "system" }
: null);
@@ -1457,7 +1459,8 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
// rewrites the one offending role to a single target and forwards
// exactly once; the sequence is fixed (never a loop), hard-capped
// at original + 2 retries. Any other failure stops the ladder and
- // the original 400 passes through verbatim.
+ // the original 400 passes through verbatim, except that an
+ // explicit content verdict from a later hop takes precedence.
// (#1996): placement-only errors that name no role enter here
// directly as { role: "system" } (see above) and skip the
// identity hop straight to the system→user placement fix.
@@ -1506,6 +1509,20 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
}
}
r.clearTimer();
+ if (errText !== null && parseContentRejection(r.response.status, errText) !== null) {
+ // A repair can itself receive a terminal verdict. Preserve
+ // that response and stop before the placement fallback.
+ upstreamResult.clearTimer();
+ upstreamResult = {
+ ...r,
+ response: new Response(errText, {
+ status: r.response.status,
+ statusText: r.response.statusText,
+ headers: new Headers(r.response.headers),
+ }),
+ };
+ return "other";
+ }
return errText !== null && detectSystemPlacementError(r.response.status, errText) ? "placement-400" : "other";
};
// #1996: an already-system offender needs no identity hop — go
@@ -1527,7 +1544,8 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
// origin+model pair process-locally (src/pck-probe.ts; surfaced via log /
// acp_status / web panel), every later prepare withholds the key there
// until proxy restart. Still failing ⇒ NOT this field — discard the
- // second response, forward the original 400 verbatim, learn nothing (the
+ // second response unless it is an explicit content verdict, forward the
+ // selected error verbatim, learn nothing (the
// next turn carries the key again and re-runs the probe). One attempt per
// request, no loops; the error body is buffered so the passthrough below
// re-reads the same bytes (same pattern as the #552 ladder above).
@@ -1577,7 +1595,10 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
if (contentWall) {
log("debug", `[${prepared.session.id}] [pck] 400 names a content wall (${pckInspection!.imageCountCap !== undefined ? `image count > ${pckInspection!.imageCountCap}` : "context overflow"}) — prompt_cache_key exonerated by inspection, A/B probe skipped (#4124)`);
}
- if (strippedPckBody !== null && !contentWall) {
+ const contentRejected = parseContentRejection(400, pckErrText) !== null;
+ // Removing a routing key cannot resolve an explicit content rejection.
+ // Preserve the first error and leave the cache-routing registry unchanged.
+ if (strippedPckBody !== null && !contentWall && !contentRejected) {
let retried: Awaited> | null = null;
try {
retried = await fetchWithTimeout(upstreamUrl, { ...init, body: await finalizeEgress(strippedPckBody) }, undefined, clientAbort.signal);
@@ -1601,15 +1622,29 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
log("info", `[${prepared.session.id}] [pck] egress carried prompt_cache_key \u2192 400; identical request without the key was accepted — withholding the key for ${maskUrlForLog(upstreamUrl)} until proxy restart (#2645)`);
upstreamResult = retried;
} else {
+ let retryErrText: string | null = null;
if (retried.response.body) {
try {
- await readStreamToBuffer(retried.response.body);
+ retryErrText = (await readStreamToBuffer(retried.response.body)).toString("utf8");
} catch {
- /* discarded either way */
+ /* unreadable retry — preserve the original error */
}
}
retried.clearTimer();
- log("debug", `[${prepared.session.id}] [pck] A/B retry without prompt_cache_key also failed (${retried.response.status}) — not the key's fault; key stays, original 400 forwarded (#2645)`);
+ if (retryErrText !== null && parseContentRejection(retried.response.status, retryErrText) !== null) {
+ upstreamResult.clearTimer();
+ upstreamResult = {
+ ...retried,
+ response: new Response(retryErrText, {
+ status: retried.response.status,
+ statusText: retried.response.statusText,
+ headers: new Headers(retried.response.headers),
+ }),
+ };
+ log("debug", `[${prepared.session.id}] [pck] retry received a terminal content verdict — preserving it without learning a key ablation`);
+ } else {
+ log("debug", `[${prepared.session.id}] [pck] A/B retry without prompt_cache_key also failed (${retried.response.status}) — not the key's fault; key stays, original 400 forwarded (#2645)`);
+ }
}
}
}
@@ -1621,8 +1656,8 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
// re-send once with exactly those blocks dropped. Accepted ⇒ causation
// confirmed: adopt the retry, remember the strict posture for THIS session
// only (later sends drop proactively above). Still failing ⇒ NOT this field
- // — discard the second response, forward the original 400 verbatim, learn
- // nothing (same controlled-experiment discipline as the #2645 ladder).
+ // — discard the second response unless it is an explicit content verdict,
+ // forward the selected error verbatim, learn nothing (as in #2645).
// Never-signing relays (#5495) word their 400 differently ("must be passed
// back"), so they never enter this branch and keep their verbatim replay.
if (
@@ -1651,7 +1686,7 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
clearTimer: upstreamResult.clearTimer,
stopIdleTimer: upstreamResult.stopIdleTimer,
};
- if (detectThinkingSignatureRejection(400, tsErrText)) {
+ if (parseContentRejection(400, tsErrText) === null && detectThinkingSignatureRejection(400, tsErrText)) {
const dropped = stripUnsignedThinkingFromWire(wireBody);
if (dropped.removed > 0) {
let retried: Awaited> | null = null;
@@ -1673,15 +1708,29 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
log("info", `[${prepared.session.id}] [thinking-posture] upstream rejected signature-less thinking ("${tsErrText.slice(0, 120)}") — stripped ${dropped.removed} block(s), retry accepted; dropping them proactively for this session (#5998)`);
upstreamResult = retried;
} else {
+ let retryErrText: string | null = null;
if (retried.response.body) {
try {
- await readStreamToBuffer(retried.response.body);
+ retryErrText = (await readStreamToBuffer(retried.response.body)).toString("utf8");
} catch {
- /* discarded either way */
+ /* unreadable retry — preserve the original error */
}
}
retried.clearTimer();
- log("warn", `[${prepared.session.id}] [thinking-posture] strip-and-resend probe also failed (${retried.response.status}) — not the unsigned blocks' fault; original 400 forwarded verbatim, nothing learned (#5998)`);
+ if (retryErrText !== null && parseContentRejection(retried.response.status, retryErrText) !== null) {
+ upstreamResult.clearTimer();
+ upstreamResult = {
+ ...retried,
+ response: new Response(retryErrText, {
+ status: retried.response.status,
+ statusText: retried.response.statusText,
+ headers: new Headers(retried.response.headers),
+ }),
+ };
+ log("warn", `[${prepared.session.id}] [thinking-posture] retry received a terminal content verdict — preserving it without learning a strict posture`);
+ } else {
+ log("warn", `[${prepared.session.id}] [thinking-posture] strip-and-resend probe also failed (${retried.response.status}) — not the unsigned blocks' fault; original 400 forwarded verbatim, nothing learned (#5998)`);
+ }
}
}
}
@@ -2122,7 +2171,8 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
// #2169: match BOTH field spellings — the chat wire says
// reasoning_content, DeepSeek's Responses wire says reasoning_text.
// #5495: DeepSeek's Anthropic-wire endpoint spells it content[].thinking.
- if (upstream.status === 400 && /reasoning_(?:content|text)|content\[\]\.thinking/i.test(errText)) {
+ // A terminal content verdict may quote these fields without establishing a schema constraint.
+ if (upstream.status === 400 && parseContentRejection(upstream.status, errText) === null && /reasoning_(?:content|text)|content\[\]\.thinking/i.test(errText)) {
if (s.metadata.strictReasoningEcho !== true) {
s.metadata.strictReasoningEcho = true;
markDirty(s);
diff --git a/src/util.ts b/src/util.ts
index 9f05351d4c..683ce05d6e 100644
--- a/src/util.ts
+++ b/src/util.ts
@@ -543,6 +543,7 @@ function parseOverflowCounts(text: string): { total?: number; messages?: number;
* rejection under 502/503 rather than 400 (#2484). */
export function inspectContextOverflow(status: number, bodyText: string): ContextOverflowInfo {
const message = (bodyText ?? "").slice(0, 300);
+ if (parseContentRejection(status, bodyText)) return { isOverflow: false, message };
const plausible = status === 400 || status === 413 || status >= 500;
if (!plausible) return { isOverflow: false, message };
if (!bodyText) return { isOverflow: false, message };
@@ -569,6 +570,38 @@ export function inspectContextOverflow(status: number, bodyText: string): Contex
};
}
+export interface ContentRejection {
+ code?: string;
+ type?: string;
+ message: string;
+}
+
+/** A structured content rejection is not evidence of a bad cache key or context size.
+ * Match the provider's explicit identity, never words quoted inside its message. */
+export function parseContentRejection(status: number, bodyText: string, requestId?: string): ContentRejection | null {
+ if (status !== 400) return null;
+ try {
+ const body: unknown = JSON.parse(bodyText);
+ if (typeof body !== "object" || body === null || !("error" in body)) return null;
+ const error = body.error;
+ if (typeof error !== "object" || error === null) return null;
+ const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
+ const type = "type" in error && typeof error.type === "string" ? error.type : undefined;
+ if (code !== "content-blocked" && type !== "agent_router_content_blocked") return null;
+ let message = "message" in error && typeof error.message === "string" ? error.message : bodyText;
+ const requestIds = [requestId];
+ for (const envelope of [body, error]) {
+ if ("request_id" in envelope && typeof envelope.request_id === "string") requestIds.push(envelope.request_id);
+ }
+ for (const id of requestIds) {
+ if (id && !message.includes(id)) message += `\nRequest ID: ${id}`;
+ }
+ return { code, type, message };
+ } catch {
+ return null;
+ }
+}
+
// #4452: an intermediate gateway that rewrites a payload-size rejection into one
// generic body (Cherry Studio et al. strip the token counts / window) makes
// inspectContextOverflow return isOverflow:false even when the payload really
diff --git a/tests/anthropic-thinking-replay.test.ts b/tests/anthropic-thinking-replay.test.ts
index 525a649e25..874a8ab2c2 100644
--- a/tests/anthropic-thinking-replay.test.ts
+++ b/tests/anthropic-thinking-replay.test.ts
@@ -201,6 +201,28 @@ test("issue #221/#5495: an attempt that SAW a signature keeps the requirement
}
});
+test("content rejection does not strip signed thinking or resend the same task", async () => {
+ const captured: CapturedRequest[] = [];
+ const error = { code: "content-blocked", type: "agent_router_content_blocked", message: "Synthetic rejection; request id: fixture-thinking" };
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (_input, init) => {
+ captured.push({ body: JSON.parse(String(init?.body)) });
+ return new Response(JSON.stringify({ error }), { status: 400 });
+ };
+ try {
+ const output = await drain(new Response(round1Thinking(true)).body!, makeCtx(), captured);
+ assert.equal(captured.length, 1, "a content rejection cannot be repaired by removing thinking");
+ assert.equal(assistantThinkingBlocks(captured[0].body).length, 1, "preserve the original signed thinking");
+ const events = output.split("\n").filter((line) => line.startsWith("data: {")).map((line) => JSON.parse(line.slice(6)));
+ const failure = events.find((event) => event.type === "error");
+ assert.equal(failure?.error.type, error.type);
+ assert.equal(failure?.error.code, error.code);
+ assert.equal(failure?.error.message, error.message);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
test("issue #221: degraded retry also rejected → error surfaced (visible failure, not a silent stop)", async () => {
const captured: CapturedRequest[] = [];
let fetchCalls = 0;
diff --git a/tests/content-rejection-compat.test.ts b/tests/content-rejection-compat.test.ts
new file mode 100644
index 0000000000..deb3021267
--- /dev/null
+++ b/tests/content-rejection-compat.test.ts
@@ -0,0 +1,77 @@
+import assert from "node:assert/strict";
+import http from "node:http";
+import { once } from "node:events";
+import test from "node:test";
+import { defaultConfig } from "acp-kernel";
+import { startServer } from "../src/server.ts";
+import { SessionStore, _setStoreForTest } from "../src/persist.ts";
+import { _setForTest as setRegistryForTest } from "../src/registry.ts";
+import { _resetSessionsForTest, getSession } from "../src/session.ts";
+
+// P0c: structured content rejection outranks diagnostic words quoted in its
+// message, including a verdict returned by an otherwise legitimate repair.
+for (const repair of ["role", "pck", "overflow-cap"] as const) {
+ for (const pluginMode of [false, true]) {
+ for (const duringRepair of [false, true]) {
+ test(`content rejection stops ${repair} repair (plugin=${pluginMode}, duringRepair=${duringRepair})`, async () => {
+ const captured: Record[] = [];
+ const rejection = JSON.stringify({ error: {
+ code: "content-blocked", type: "agent_router_content_blocked",
+ message: (duringRepair ? "Rejected source quotes: System message must be at the beginning." : "Rejected source quotes: Invalid role: developer") + " Quoted reasoning_content, reasoning_text, content[].thinking; maximum context length exceeded.",
+ } });
+ const upstream = http.createServer((req, res) => {
+ const chunks: Buffer[] = [];
+ req.on("data", (chunk: Buffer) => chunks.push(chunk));
+ req.on("end", () => {
+ captured.push(JSON.parse(Buffer.concat(chunks).toString("utf8")));
+ const initialValidationError = duringRepair && captured.length === 1;
+ res.writeHead(400, { "content-type": "application/json", "x-request-id": initialValidationError ? "initial-validation" : "content-verdict" });
+ res.end(initialValidationError ? JSON.stringify({ error: { type: "invalid_request_error", message: repair === "role" ? "Invalid role: developer" : repair === "pck" ? "Unsupported parameter(s): prompt_cache_key" : "Requested token count exceeds the model's maximum context length of 100000 tokens. You requested a total of 110000 tokens: 90000 tokens from the input messages and 20000 tokens for the completion." } }) : rejection);
+ });
+ });
+ upstream.listen(0, "127.0.0.1");
+ await once(upstream, "listening");
+ const ua = upstream.address();
+ assert.ok(ua && typeof ua === "object");
+ _resetSessionsForTest();
+ _setStoreForTest(new SessionStore({ enabled: false }));
+ setRegistryForTest({});
+ const proxy = await startServer({
+ port: 0, host: "127.0.0.1", upstream: "http://127.0.0.1",
+ routes: { [`http://127.0.0.1:${ua.port}`]: { models: { "gpt-test": { context: 100000 } } } },
+ modelContextLimit: 100000, kernelConfig: defaultConfig(100000),
+ compress: { injectTool: true, injectNudge: true }, promptCache: { routing: "auto" },
+ log: false, sessionHeader: "x-acp-session", debug: false, passthrough: false, autoUpdate: false,
+ mitm: { enabled: false, domains: [] }, compat: { roles: {} }, streamErrorShape: "protocol",
+ passthroughSource: null, autoRestartOnUpdate: false, updateTag: "latest", advisoryCheck: false, releaseNotesCheck: false,
+ });
+ if (!proxy.listening) await once(proxy, "listening");
+ const pa = proxy.address();
+ assert.ok(pa && typeof pa === "object");
+ try {
+ const sid = `content-${repair}-${pluginMode}-${duringRepair}`;
+ const response = await fetch(`http://127.0.0.1:${pa.port}/bili/http://127.0.0.1:${ua.port}/v1/responses`, {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-acp-session": sid, ...(pluginMode ? { "x-bili-plugin": "dsh", "x-bili-plugin-conversation": sid } : {}) },
+ body: JSON.stringify({ model: "gpt-test", stream: true, ...(repair === "overflow-cap" ? { max_output_tokens: 20000 } : {}), ...(repair === "pck" ? { prompt_cache_key: "compat-test" } : {}), input: [
+ { type: "message", role: "developer", content: "Be concise." },
+ { type: "message", role: "user", content: "hello" },
+ ] }),
+ });
+ const text = await response.text();
+ assert.equal(captured.length, duringRepair ? 2 : 1, "no sends after the terminal content verdict");
+ assert.equal(response.status, 400);
+ assert.equal(text, rejection, "the terminal verdict must not be replaced by the earlier validation error");
+ assert.equal(response.headers.get("x-request-id"), "content-verdict");
+ assert.notEqual(getSession(sid).metadata.strictReasoningEcho, true, "quoted diagnostics in a content verdict must not teach reasoning compatibility");
+ if (repair === "overflow-cap" && duringRepair) {
+ assert.deepEqual(captured.map(body => body.max_output_tokens), [20000, 10000], "the legitimate output-budget retry is preserved");
+ }
+ } finally {
+ const pc = once(proxy, "close"); proxy.close(); proxy.closeIdleConnections(); await pc;
+ const uc = once(upstream, "close"); upstream.close(); upstream.closeIdleConnections(); await uc;
+ }
+ });
+ }
+ }
+}
diff --git a/tests/issue2645-pck-probe.test.ts b/tests/issue2645-pck-probe.test.ts
index 59950d14da..fa5cf704e0 100644
--- a/tests/issue2645-pck-probe.test.ts
+++ b/tests/issue2645-pck-probe.test.ts
@@ -38,12 +38,14 @@ interface Harness {
upstreamPort: number;
captured: Captured[];
setStrictness(mode: Strictness): void;
+ setRejectionBody(body: string): void;
close(): Promise;
}
async function startHarness(strictModels?: Set): Promise {
const captured: Captured[] = [];
let strictness: Strictness = "lenient";
+ let rejectionBody: string | undefined;
const upstream = http.createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (c: Buffer) => chunks.push(c));
@@ -51,6 +53,11 @@ async function startHarness(strictModels?: Set): Promise {
let body: Record = {};
try { body = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { /* keep {} */ }
captured.push({ headers: req.headers, body });
+ if (rejectionBody !== undefined) {
+ res.writeHead(400, { "content-type": "application/json", "x-request-id": "synthetic-content-rejection" });
+ res.end(rejectionBody);
+ return;
+ }
const hasKey = typeof body.prompt_cache_key === "string";
// #2645 evidence table: NVIDIA's strictness is MODEL-level on one
// origin — honor an explicit strict-model set when given.
@@ -103,6 +110,7 @@ async function startHarness(strictModels?: Set): Promise {
upstreamPort,
captured,
setStrictness: (mode) => { strictness = mode; },
+ setRejectionBody: (body) => { rejectionBody = body; },
close: async () => {
proxy.close();
proxy.closeIdleConnections?.();
@@ -207,6 +215,39 @@ test("#2645 probe: unrelated persistent 400 is NOT attributed to the key — key
}
});
+for (const protocol of ["openai", "responses"] as const) {
+ for (const errorIdentity of [{ code: "content-blocked" }, { type: "agent_router_content_blocked" }]) {
+ test(`${protocol}: explicit content rejection is preserved without a cache-key probe (${JSON.stringify(errorIdentity)})`, async () => {
+ const h = await startHarness();
+ try {
+ const rejection = JSON.stringify({ error: { ...errorIdentity, message: "Synthetic content rejection; request id: fixture-01" } });
+ h.setRejectionBody(rejection);
+ const endpoint = protocol === "responses" ? "responses" : "chat/completions";
+ const body = {
+ model: "gpt-test", stream: true, prompt_cache_key: "content-rejection-key",
+ ...(protocol === "responses"
+ ? { input: [{ role: "user", content: "Explain a plugin migration plan." }] }
+ : { messages: [{ role: "user", content: "Explain a plugin migration plan." }] }),
+ };
+ const url = `http://127.0.0.1:${h.proxyPort}/bili/http://127.0.0.1:${h.upstreamPort}/v1/${endpoint}`;
+ for (let attempt = 1; attempt <= 2; attempt++) {
+ const response = await fetch(url, {
+ method: "POST", headers: { "content-type": "application/json", "x-acp-session": `content-rejection-${protocol}` },
+ body: JSON.stringify(body),
+ });
+ assert.equal(response.status, 400);
+ assert.equal(await response.text(), rejection, "preserve the original error and request identifier");
+ assert.equal(h.captured.length, attempt, "one upstream send per client request; no internal probe");
+ assert.equal(h.captured.at(-1)?.body.prompt_cache_key, "content-rejection-key");
+ assert.equal(pckAblations().length, 0, "content rejection must not change cache routing");
+ }
+ } finally {
+ await h.close();
+ }
+ });
+ }
+}
+
test("#2645 probe: model-level granularity — sibling model on the same strict origin keeps the key", async () => {
const h = await startHarness(new Set(["nim-550b"]));
try {
diff --git a/tests/issue4452-markerless-reject.test.ts b/tests/issue4452-markerless-reject.test.ts
index d3bd1c9749..ec73a3a954 100644
--- a/tests/issue4452-markerless-reject.test.ts
+++ b/tests/issue4452-markerless-reject.test.ts
@@ -1,6 +1,6 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { inspectContextOverflow, isMarkerlessOverflowReject } from "../src/util.ts";
+import { inspectContextOverflow, isMarkerlessOverflowReject, parseContentRejection } from "../src/util.ts";
// #4452: an intermediate gateway that rewrites a payload-size rejection into one
// generic body (Cherry Studio strips the token counts / window) defeats the
@@ -34,6 +34,40 @@ const OPENAI_OVERFLOW_BODY = JSON.stringify({
const CJK_OVERFLOW_BODY = JSON.stringify({ error: { message: "上下文长度超出限制", type: "invalid_request_error" } });
+test("explicit content rejection takes precedence over quoted overflow and image diagnostics", () => {
+ const message = "Quoted context_length_exceeded; Too many images: maximum 5 images. request id: fixture-classify";
+ for (const identity of [{ code: "content-blocked" }, { type: "agent_router_content_blocked" }]) {
+ const body = JSON.stringify({ error: { ...identity, message } });
+ assert.equal(parseContentRejection(400, body)?.message, message);
+ assert.deepEqual(inspectContextOverflow(400, body), { isOverflow: false, message: body.slice(0, 300) });
+ assert.equal(isMarkerlessOverflowReject(400, body), false);
+ }
+});
+
+test("quoted markers, malformed envelopes and other HTTP statuses are not explicit content rejection", () => {
+ const bodies = [
+ "content-blocked", "null", "[]", "{}", '{"error":null}',
+ JSON.stringify({ error: { message: "content-blocked agent_router_content_blocked", code: "bad_request" } }),
+ JSON.stringify({ error: { code: { value: "content-blocked" }, type: ["agent_router_content_blocked"] } }),
+ OPENAI_OVERFLOW_BODY, CJK_OVERFLOW_BODY, MALFORMED_BODY, GENERIC_BODY,
+ ];
+ for (const body of bodies) assert.equal(parseContentRejection(400, body), null, body);
+ for (const status of [200, 401, 403, 413, 429, 500, 503]) {
+ assert.equal(parseContentRejection(status, '{"error":{"code":"content-blocked"}}'), null);
+ }
+});
+
+test("content rejection retains request IDs carried outside the message", () => {
+ for (const envelope of [
+ { error: { code: "content-blocked", message: "Synthetic rejection", request_id: "fixture-nested-id" } },
+ { error: { code: "content-blocked", message: "Synthetic rejection" }, request_id: "fixture-root-id" },
+ ]) {
+ const body = JSON.stringify(envelope);
+ assert.ok(body.length < 200, "the previous diagnostic retained these short bodies");
+ assert.match(parseContentRejection(400, body)?.message ?? "", /fixture-(nested|root)-id/);
+ }
+});
+
test("generic gateway body on 413 is the markerless SIZE verdict and is flagged", () => {
// The first-order failure: the marker gate itself says "not overflow".
assert.equal(inspectContextOverflow(413, GENERIC_BODY).isOverflow, false);
diff --git a/tests/issue5998-unsigned-thinking-egress.test.ts b/tests/issue5998-unsigned-thinking-egress.test.ts
index 16e88ae076..77123f62d1 100644
--- a/tests/issue5998-unsigned-thinking-egress.test.ts
+++ b/tests/issue5998-unsigned-thinking-egress.test.ts
@@ -190,18 +190,25 @@ interface Rig {
messagesUrl: () => string;
upstreamBodies: string[];
setPersonality(mode: Personality): void;
+ setContentRejected(afterRequests?: number): void;
closeAll(): Promise;
}
async function startRig(): Promise {
const upstreamBodies: string[] = [];
let personality: Personality = "lenient";
+ let contentRejectedAfter = Infinity;
const upstream = http.createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (c: Buffer) => chunks.push(c));
req.on("end", () => {
const raw = Buffer.concat(chunks).toString("utf8");
upstreamBodies.push(raw);
+ if (upstreamBodies.length > contentRejectedAfter) {
+ res.writeHead(400, { "content-type": "application/json", "x-request-id": "thinking-content-verdict" });
+ res.end(JSON.stringify({ error: { code: "content-blocked", type: "agent_router_content_blocked", message: WORDINGS["poisoned-signature"] } }));
+ return;
+ }
const rejectWith = (message: string): void => {
res.writeHead(400, { "content-type": "application/json" });
res.end(JSON.stringify({ type: "error", error: { type: "invalid_request_error", message } }));
@@ -261,6 +268,7 @@ async function startRig(): Promise {
messagesUrl: () => `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/v1/messages`,
upstreamBodies,
setPersonality: (mode) => { personality = mode; },
+ setContentRejected: (afterRequests = 0) => { contentRejectedAfter = afterRequests; },
closeAll: async () => {
await closeOne(proxy);
await closeOne(upstream);
@@ -293,6 +301,25 @@ async function post(rig: Rig, sid: string): Promise {
});
}
+for (const afterRequests of [0, 1]) {
+ test(`content rejection quoting signature diagnostics stops thinking repair (after=${afterRequests})`, async () => {
+ const rig = await startRig();
+ try {
+ rig.setPersonality("strict");
+ rig.setContentRejected(afterRequests);
+ const response = await post(rig, "ts-content-rejection");
+ const body = await response.json();
+ assert.equal(response.status, 400);
+ assert.deepEqual(body, { error: { code: "content-blocked", type: "agent_router_content_blocked", message: WORDINGS["poisoned-signature"] } });
+ assert.equal(response.headers.get("x-request-id"), "thinking-content-verdict");
+ assert.equal(bodyHasUnsignedThinking(rig.upstreamBodies[0]!), true, "exercise the actual strip-probe admission");
+ assert.equal(rig.upstreamBodies.length, afterRequests + 1, "no sends after the terminal content verdict");
+ } finally {
+ await rig.closeAll();
+ }
+ });
+}
+
test("#5998 e2e: strict upstream self-heals in one turn; later turns drop proactively", async () => {
const rig = await startRig();
try {
diff --git a/tests/loop-adapters.test.ts b/tests/loop-adapters.test.ts
index f89e4f0ff7..6c6dbde8a5 100644
--- a/tests/loop-adapters.test.ts
+++ b/tests/loop-adapters.test.ts
@@ -3,12 +3,50 @@ import assert from "node:assert/strict";
import type { Config, CoreMessage } from "acp-kernel";
import { createCore, createInitialState } from "acp-kernel";
import type { Session } from "../src/session.ts";
-import { runCompressLoop, createOpenaiAdapter, createAnthropicAdapter, createResponsesAdapter } from "../src/loop/index.ts";
+import { runCompressLoop, createOpenaiAdapter, createAnthropicAdapter, createResponsesAdapter, createGoogleAdapter } from "../src/loop/index.ts";
+import { createCommandcodeAdapter } from "../src/loop/adapter-commandcode.ts";
import type { ParsedStreamEvent } from "../src/loop/index.ts";
import { buildCompressSystemPrompt } from "../src/compress-tool.ts";
import { responsesToCore } from "acp-kernel/wire";
import type { ResponsesRequestBody, AnthropicTextBlock } from "acp-kernel/wire";
+test("native loop error frames retain content rejection identity and complete diagnostic", () => {
+ const rejection = { code: "content-blocked", type: "agent_router_content_blocked", message: "Synthetic diagnostic: " + "detail ".repeat(40) + "request id: fixture-adapter" };
+ const frames = (text: string) => text.split("\n").filter((line) => line.startsWith("data: {")).map((line) => JSON.parse(line.slice(6)));
+ const responses = frames(createResponsesAdapter().emitError(rejection.message, rejection).toString());
+ const failed = responses.find((frame) => frame.type === "response.failed");
+ assert.deepEqual(failed?.response.error, { code: rejection.code, message: rejection.message });
+ for (const adapter of [createOpenaiAdapter({ model: "test" }), createAnthropicAdapter({ model: "test" })]) {
+ const failure = frames(adapter.emitError(rejection.message, rejection).toString()).find((frame) => frame.error);
+ assert.deepEqual(failure?.error, rejection);
+ }
+ const google = frames(createGoogleAdapter({}).emitError(rejection.message, rejection).toString())[0];
+ assert.deepEqual(google.error, { code: 400, status: "INVALID_ARGUMENT", message: rejection.message });
+ const commandcode = JSON.parse(createCommandcodeAdapter({}).emitError(rejection.message, rejection).toString());
+ assert.deepEqual(commandcode, { type: "error", error: rejection.code, message: rejection.message });
+
+ const typeOnly = { type: rejection.type, message: rejection.message };
+ const typeOnlyFrames = frames(createResponsesAdapter().emitError(typeOnly.message, typeOnly).toString());
+ assert.equal(typeOnlyFrames.find((frame) => frame.type === "response.failed")?.response.error.code, typeOnly.type);
+ const generic = frames(createResponsesAdapter().emitError("transport failed").toString());
+ assert.equal(generic.find((frame) => frame.type === "response.failed")?.response.error.code, "server_error");
+});
+
+for (const terminal of [false, true]) {
+ test(`anthropic start output is retained and cumulative delta replaces it (terminal=${terminal})`, async () => {
+ const frame = (type: string, data: unknown) => `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`;
+ const start = frame("message_start", { type: "message_start", message: { id: "partial-usage", usage: { input_tokens: 5, output_tokens: 2, cache_read_input_tokens: 0 } } });
+ const end = terminal ? frame("message_delta", { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 5 } }) + frame("message_stop", { type: "message_stop" }) : "";
+ const events: ParsedStreamEvent[] = [];
+ for await (const event of createAnthropicAdapter({ model: "test" }).parseStream(new Response(start + end).body!, 1)) events.push(event);
+ const usage = events.filter((event) => event.kind === "usage");
+ assert.equal(usage.length, 1, "one measurement, including at EOF");
+ assert.equal(usage[0].inputTokens, 5);
+ assert.equal(usage[0].outputTokens, terminal ? 5 : 2, "delta is cumulative, not added to the start count");
+ assert.equal(events.some((event) => event.kind === "done"), terminal, "EOF must not invent completion");
+ });
+}
+
function makeCtx(id: string, messages: CoreMessage[] = []): {
core: ReturnType;
config: Config;
diff --git a/tests/loop-compress.test.ts b/tests/loop-compress.test.ts
index ac3cb7807a..97f4f4f0a9 100644
--- a/tests/loop-compress.test.ts
+++ b/tests/loop-compress.test.ts
@@ -702,6 +702,41 @@ test("loop #10 (S3): upstream 500 mid-loop terminates cleanly (timer cleared, no
// compress fold (host refreshFolded hook), not the stale pre-compress view.
// The stale view is what made the model stop: it was told "~N tokens saved"
// while staring at the identical context it had just compressed.
+test("loop: content rejection after committed compression preserves error identity and the committed block", async () => {
+ const ctx = withRefs(makeCtx([
+ textMsg("raw_1", "user", bigText(5000)),
+ textMsg("raw_2", "assistant", bigText(5000)),
+ textMsg("raw_3", "user", bigText(5000)),
+ textMsg("raw_4", "assistant", bigText(5000)),
+ textMsg("raw_5", "user", bigText(5000)),
+ textMsg("raw_6", "assistant", bigText(5000)),
+ textMsg("raw_7", "user", bigText(5000)),
+ ]));
+ const summary = "Synthetic migration task: continue the authorized implementation; earlier analysis is complete.";
+ const args = JSON.stringify({ content: [{ startId: "m00001", endId: "m00002", summary }] });
+ const round1 = sse("response.created", { response: { id: "resp_1", status: "in_progress" } })
+ + fcEvents(0, "call_content_reject", "compress", args) + COMPLETED;
+ const error = { code: "content-blocked", type: "agent_router_content_blocked", message: "Synthetic rejection. " + "detail ".repeat(40) + "request id: fixture-after-compress" };
+ const originalFetch = globalThis.fetch;
+ let sends = 0;
+ let refreshes = 0;
+ ctx.refreshFolded = (messages) => { refreshes++; return messages; };
+ globalThis.fetch = async () => { sends++; return new Response(JSON.stringify({ error }), { status: 400 }); };
+ try {
+ const output = await drain(new Response(round1).body!, ctx,
+ { model: "gpt-test", input: [], stream: true }, { url: "http://mock", headers: {} });
+ assert.equal(sends, 1, "explicit rejection must not replay the committed operation");
+ assert.equal(refreshes, 1, "compression completed before rejection");
+ assert.ok(ctx.session.state.blocks.some((block) => block.summary === summary), "keep the committed summary");
+ const events = output.split("\n").filter((line) => line.startsWith("data: {")).map((line) => JSON.parse(line.slice(6)));
+ const failure = events.find((event) => event.type === "response.failed");
+ assert.equal(failure?.response.error.code, error.code, "do not relabel a content rejection as server_error");
+ assert.equal(failure?.response.error.message, error.message, "retain the full diagnostic and trailing request id");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
test("loop #422a: successful compress → re-request carries the refreshed fold + round records", async () => {
// 7 messages: kernel protects the last 5, so m00001/m00002 are compressible.
const ctx = withRefs(
diff --git a/tests/loop-core.test.ts b/tests/loop-core.test.ts
index e420605678..52a7876b94 100644
--- a/tests/loop-core.test.ts
+++ b/tests/loop-core.test.ts
@@ -577,6 +577,10 @@ test("replay retry: 429 then success → retried", async () => {
});
test("isTransientUpstreamError: classifier matrix", () => {
+ for (const identity of [{ code: "content-blocked" }, { type: "agent_router_content_blocked" }]) {
+ const body = JSON.stringify({ error: { ...identity, message: "Risk control: please retry; try again" } });
+ assert.equal(isTransientUpstreamError(400, body), false, "explicit content rejection outranks generic transient wording");
+ }
assert.equal(isTransientUpstreamError(400, CAPTCHA_400_BODY), true, "captcha 400 is transient");
assert.equal(isTransientUpstreamError(400, '{"error":{"message":"Invalid model"}}'), false, "plain 400 is not");
assert.equal(isTransientUpstreamError(401, ""), false, "401 never retried");
diff --git a/tests/loop-degenerate-retry.test.ts b/tests/loop-degenerate-retry.test.ts
index 5f340a634d..e86dbca5f5 100644
--- a/tests/loop-degenerate-retry.test.ts
+++ b/tests/loop-degenerate-retry.test.ts
@@ -69,7 +69,7 @@ const ROUND_GOOD = [
sse("response.completed", { response: { id: "resp_3", status: "completed", output: [] } }),
].join("");
-async function drain(retries: string[], id: string): Promise<{ out: string; fetchCalls: number; bodies: string[] }> {
+async function drain(retries: Array }>, id: string): Promise<{ out: string; fetchCalls: number; bodies: string[] }> {
let fetchCalls = 0;
const bodies: string[] = [];
const orig = globalThis.fetch;
@@ -77,7 +77,7 @@ async function drain(retries: string[], id: string): Promise<{ out: string; fetc
fetchCalls++;
if (init?.body !== undefined) bodies.push(typeof init.body === "string" ? init.body : String(init.body));
const body = retries[fetchCalls - 1] ?? "";
- return new Response(body, { status: 200 });
+ return typeof body === "string" ? new Response(body, { status: 200 }) : new Response(body.body, body);
}) as typeof fetch;
const chunks: Buffer[] = [];
try {
@@ -98,6 +98,19 @@ async function drain(retries: string[], id: string): Promise<{ out: string; fetc
return { out: Buffer.concat(chunks).toString("utf8"), fetchCalls, bodies };
}
+test("a recovery request rejected for content ends as a failure with body and header request IDs", async () => {
+ const error = { code: "content-blocked", request_id: "fixture-body-id", message: "Synthetic rejection" };
+ const { out, fetchCalls } = await drain([ROUND_DEGENERATE, {
+ status: 400, body: JSON.stringify({ error }), headers: { "x-request-id": "fixture-header-id" },
+ }], "content-rejected-recovery");
+ assert.equal(fetchCalls, 2, "one normal continuation and one rejected recovery; no further send");
+ assert.ok(out.includes('\"code\":\"content-blocked\"'), "do not replace a rejection with a successful empty completion");
+ assert.ok(out.includes("fixture-body-id"), "retain the structured request ID");
+ assert.ok(out.includes("fixture-header-id"), "retain the transport request ID");
+ assert.ok(out.includes("response.failed"));
+ assert.ok(!out.includes("response.completed"), "no successful terminal after recovery rejection");
+});
+
test("#732 D1: degenerate post-compress turn → one invisible retry with a continuation nudge", async () => {
// fetch #1 = re-request (degenerate); fetch #2 = the auto-retry (good turn).
const { out, fetchCalls, bodies } = await drain([ROUND_DEGENERATE, ROUND_GOOD], "deg-d1");
@@ -359,17 +372,22 @@ test("#1862 B1: both attempts' usage settled exactly once (replaced attempt no l
assert.equal(getCacheLedger(session).lines.length, 2, "one ledger sample per attempt — neither dropped nor double-counted");
});
-test("#1862 B2: failed degenerate-retry fetch settles the original attempt exactly once, fabricates nothing", async () => {
- const prevMax = process.env.BILI_REPLAY_RETRY_MAX;
- process.env.BILI_REPLAY_RETRY_MAX = "1";
- try {
- const { fetchCalls, session } = await drainResp(DEGENERATE_USAGE, [() => new Response("upstream exploded", { status: 500 })], "b2");
- assert.equal(fetchCalls, 1, "the degenerate retry fetched once and failed");
- assert.equal(session.stats.inputTokens, 100, "original attempt's input settled exactly once (not double-counted on failure)");
- assert.equal(session.stats.outputTokens, 5, "original attempt's output settled exactly once");
- assert.equal(getCacheLedger(session).lines.length, 1, "exactly one ledger sample — no fabricated usage for the failed fetch");
- } finally {
- if (prevMax === undefined) delete process.env.BILI_REPLAY_RETRY_MAX;
- else process.env.BILI_REPLAY_RETRY_MAX = prevMax;
- }
-});
+for (const failure of [
+ { label: "500", status: 500, body: "upstream exploded" },
+ { label: "content rejection", status: 400, body: JSON.stringify({ error: { code: "content-blocked", message: "Synthetic rejection" } }) },
+]) {
+ test(`#1862 B2: ${failure.label} settles the original attempt exactly once, fabricates nothing`, async () => {
+ const prevMax = process.env.BILI_REPLAY_RETRY_MAX;
+ process.env.BILI_REPLAY_RETRY_MAX = "1";
+ try {
+ const { fetchCalls, session } = await drainResp(DEGENERATE_USAGE, [() => new Response(failure.body, { status: failure.status })], `b2-${failure.status}`);
+ assert.equal(fetchCalls, 1, "the degenerate retry fetched once and failed");
+ assert.equal(session.stats.inputTokens, 100, "original attempt's input settled exactly once (not double-counted on failure)");
+ assert.equal(session.stats.outputTokens, 5, "original attempt's output settled exactly once");
+ assert.equal(getCacheLedger(session).lines.length, 1, "exactly one ledger sample — no fabricated usage for the failed fetch");
+ } finally {
+ if (prevMax === undefined) delete process.env.BILI_REPLAY_RETRY_MAX;
+ else process.env.BILI_REPLAY_RETRY_MAX = prevMax;
+ }
+ });
+}
diff --git a/tests/loop-truncation.test.ts b/tests/loop-truncation.test.ts
index c6cdf7e61c..fab6d81c0c 100644
--- a/tests/loop-truncation.test.ts
+++ b/tests/loop-truncation.test.ts
@@ -6,6 +6,7 @@ import type { Session } from "../src/session.ts";
import { runCompressLoop, createAnthropicAdapter } from "../src/loop/index.ts";
import { buildCompressSystemPrompt } from "../src/compress-tool.ts";
import { log as loggerLog, setLogCapture } from "../src/logger.ts";
+import { getCacheLedger } from "../src/cache-ledger.ts";
// #413: upstream truncation (200 + early SSE EOF) — zero-side-effect retry,
// well-formed Anthropic error stream (message_start before content blocks,
@@ -179,6 +180,32 @@ test("#413 T1: 0-event EOF → retried once; failed retry → well-formed error
}
});
+for (const [label, first] of [
+ ["invisible truncation", ""],
+ ["visible truncation", MESSAGE_START.replace('"output_tokens":0', '"output_tokens":2') + textStart(0) + textDelta(0, "Partial answer")],
+ ["stalled announcement", MESSAGE_START + textBlock(0, "Running verify after formatting:") + MESSAGE_DELTA() + MESSAGE_STOP],
+]) {
+ test(`content rejection during ${label} recovery stays terminal`, async () => {
+ const error = { code: "content-blocked", type: "agent_router_content_blocked", message: "Synthetic rejection: please retry; request id: fixture-recovery" };
+ const mock = mockFetch(() => new Response(JSON.stringify({ error }), { status: 400 }));
+ try {
+ const ctx = { ...makeCtx(`content-recovery-${label}`), protocol: "anthropic" as const };
+ const output = await drain(new Response(first).body!, ctx);
+ assert.equal(mock.calls(), 1, "do not retry an explicit rejection or enter another recovery");
+ const failure = output.split("\n").filter((line) => line.startsWith("data: {"))
+ .map((line) => JSON.parse(line.slice(6))).find((frame) => frame.type === "error");
+ assert.deepEqual(failure?.error, error, "preserve the content rejection instead of the original truncated or stalled turn");
+ assert.ok(!output.includes('\"stop_reason\":\"end_turn\"'), "recovery rejection is not success");
+ const measured = first.includes("message_start");
+ assert.equal(ctx.session.stats.inputTokens, measured ? 5 : 0, "retain the original attempt's reported input");
+ assert.equal(ctx.session.stats.outputTokens, label === "stalled announcement" ? 3 : label === "visible truncation" ? 2 : 0, "retain measured output without inventing rejected usage");
+ assert.equal(getCacheLedger(ctx.session).lines.length, measured ? 1 : 0, "one ledger sample per measured attempt");
+ } finally {
+ mock.restore();
+ }
+ });
+}
+
test("#413 T2: 0-event EOF → retry succeeds → one clean stream, no error surfaced", async () => {
const round2 = [MESSAGE_START, textBlock(0, "Hello retry"), MESSAGE_DELTA(), MESSAGE_STOP].join("");
const mock = mockFetch(() => new Response(round2, { status: 200 }));
diff --git a/tests/wire-contract-fakes.ts b/tests/wire-contract-fakes.ts
index ecb00b1426..f6a6c1e410 100644
--- a/tests/wire-contract-fakes.ts
+++ b/tests/wire-contract-fakes.ts
@@ -38,6 +38,13 @@ export const WIRE_RULES: readonly WireRule[] = [
summary: "Responses text/content-part SSE events carry a non-negative integer content_index identifying the part inside the indexed output item",
provenance: "OpenAI openai-node v6.26.0 requires content_index in ResponseTextDeltaEvent/ResponseTextDoneEvent/ResponseContentPartAddedEvent/ResponseContentPartDoneEvent (https://github.com/openai/openai-node/blob/v6.26.0/src/resources/responses/responses.ts); ResponseStream indexes output.content[event.content_index] (https://github.com/openai/openai-node/blob/v6.26.0/src/lib/responses/ResponseStream.ts). Reproduced against that official SDK: bili's synthesized messages, legacy stream-error completions and filtered text tails omitted indices, so finalResponse() rejected with 'missing content at index undefined'. Gates exercise the actual SDK in proxy/plugin paths and the emitted error frames; the fake validates its outgoing SSE frames with the same constraint.",
},
+ {
+ id: "WC-027",
+ wire: "responses",
+ lane: "agentrouter-content-rejected",
+ summary: "An explicit HTTP 400 content-blocked / agent_router_content_blocked verdict is terminal for the current request: preserve its diagnostic and request ID even when received by a compatibility retry; do not rewrite roles, probe the cache key, strip thinking or infer context overflow.",
+ provenance: "https://github.com/ranxianglei/billion-context/issues/6832: Codex Desktop / GPT-6 through bili 0.1.213 received the explicit verdict after committed compression, then a key-less probe failed again. The issue records the sanitized envelope; the matched content and upstream rule are unknown. This fake scripts the observed verdict, not a content-detection policy.",
+ },
{
id: "WC-017",
wire: "responses",
@@ -765,7 +772,7 @@ export interface CapturedRequest {
/** Lane-scoped fakes: a constraint that holds only on one client's or endpoint's lane lives in that lane's own
* fake, not in the wire's shared VALIDATOR (WC-017's rule-scoping precedent). */
-type FakeLane = "vertex-anthropic";
+type FakeLane = "vertex-anthropic" | "agentrouter-content-rejected";
interface FakeUpstream {
wire: Wire;
@@ -956,6 +963,14 @@ const PATH_MATCHERS: Record boolean> = {
google: (u) => /\/v1beta\/models\/[^/:]+:(streamGenerateContent|generateContent)/.test(u),
};
+/** WC-026: a scripted upstream verdict; no inferred trigger words or content policy. */
+export function contentRejectionEnvelope(): { status: number; body: string } {
+ return { status: 400, body: JSON.stringify({ error: {
+ code: "content-blocked", type: "agent_router_content_blocked",
+ message: "Synthetic content rejection (request id: wc-content-01)",
+ } }) };
+}
+
/** Start a deterministic fake upstream for one wire protocol on a random loopback port. */
export async function startFakeUpstream(wire: Wire, opts?: { replyText?: string; lane?: FakeLane }): Promise {
const replyText = opts?.replyText ?? "ok";
@@ -998,6 +1013,12 @@ export async function startFakeUpstream(wire: Wire, opts?: { replyText?: string;
res.end(env.body);
return;
}
+ if (lane === "agentrouter-content-rejected") {
+ const rejection = contentRejectionEnvelope();
+ res.writeHead(rejection.status, { "content-type": "application/json" });
+ res.end(rejection.body);
+ return;
+ }
const p = isPlainObject(parsed) ? parsed : {};
switch (wire) {
case "anthropic":
diff --git a/tests/wire-contract.test.ts b/tests/wire-contract.test.ts
index 6ccfe5e93f..2fc55f5a68 100644
--- a/tests/wire-contract.test.ts
+++ b/tests/wire-contract.test.ts
@@ -22,7 +22,7 @@ import http from "node:http";
import { once } from "node:events";
import { readFileSync } from "node:fs";
import { emitStreamError } from "../src/stream-error.ts";
-import { validateResponsesContentIndex } from "./wire-contract-fakes.ts";
+import { contentRejectionEnvelope, validateResponsesContentIndex } from "./wire-contract-fakes.ts";
process.env.NODE_ENV = "test";
@@ -390,6 +390,15 @@ test("wire-contract ledger: every lane-scoped rule has a live enforcement clause
// Lane-scoped constraints hold on ONE client's lane only — the shared wire validator
// cannot enforce them (WC-013 forbids exactly what WC-017 requires, same frame shape).
const laneProbes: Array<{ ruleId: string; validate: (body: unknown) => string[]; body: unknown }> = [
+ {
+ ruleId: "WC-027", body: null,
+ validate: () => {
+ const rejection = contentRejectionEnvelope();
+ const error = JSON.parse(rejection.body).error;
+ return rejection.status === 400 && error.code === "content-blocked" && error.type === "agent_router_content_blocked"
+ ? ["WC-027 explicit content rejection envelope"] : [];
+ },
+ },
{ ruleId: "WC-026", validate: validateResponsesContentIndex, body: { type: "response.output_text.delta", output_index: 0, delta: "x" } },
{ ruleId: "WC-017", validate: validateCodexResponsesWsCreate, body: { type: "response.create", input: [] } },
// WC-019/020/021 are the Vertex Anthropic lane (lane: "vertex-anthropic") — the wire rules that
@@ -770,6 +779,26 @@ for (const lane of LANES) {
});
}
+test("WC-027: explicit content rejection is forwarded once without a cache-key probe", async () => {
+ const lane = LANES.find((candidate) => candidate.wire === "responses")!;
+ const fake = await startFakeUpstream("responses", { lane: "agentrouter-content-rejected" });
+ let rig: Rig | undefined;
+ try {
+ rig = await startRig(fake.url, lane.model, {});
+ const response = await fetch(`${rig.proxyUrl}${lane.path}`, {
+ method: "POST", headers: { "content-type": "application/json", "x-acp-session": "wc-content" },
+ body: JSON.stringify({ ...lane.clientBody, prompt_cache_key: "wc-content-key" }),
+ });
+ assert.equal(response.status, 400);
+ assert.equal(await response.text(), contentRejectionEnvelope().body);
+ assert.equal(fake.requests.length, 1, "no internal retry for the explicit upstream verdict");
+ assert.deepEqual(fake.violations, [], "the fixture rejects content independently of wire validity");
+ } finally {
+ if (rig) await rig.close();
+ await fake.close();
+ }
+});
+
test("wire-contract D: opt-in lane (absorb+rules+ccr) forwards the extended surface legally", async () => {
const lane = LANES[0];
const fake = await startFakeUpstream(lane.wire);