Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(proxy): 加密内容剥离不再掏空上下文压缩块 (#780)
Chris Zhang0ebb3ad52fb2
diff --git a/packages/anthropic-compat-proxy/src/transform.test.ts b/packages/anthropic-compat-proxy/src/transform.test.tsindex 117fbb68be..07c232a744 100644--- a/packages/anthropic-compat-proxy/src/transform.test.ts+++ b/packages/anthropic-compat-proxy/src/transform.test.ts@@ -69,6 +69,124 @@ describe('stripEncryptedContentFromBody', () => {it('returns null for non-JSON body', () => {expect(stripEncryptedContentFromBody(Buffer.from('not json', 'utf8'))).toBeNull();});++ // 回归 (2026-07 Grok 会话卡死): 压缩块的 encrypted_content 是压缩 blob 本体,+ // 剥掉只会留下上游无法解码的空壳 → xAI 400 "Could not decode the compaction blob"。+ it('keeps the compaction blob intact while stripping reasoning blobs', () => {+ const body = buf({+ model: 'grok-4.5',+ input: [+ { type: 'compaction', id: 'cmp_abc', encrypted_content: 'BLOB' },+ { type: 'reasoning', encrypted_content: 'gAAAAABxyz...', summary: [] },+ { type: 'message', role: 'user', content: 'hi' },+ ],+ });+ const out = stripEncryptedContentFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.input).toEqual([+ { type: 'compaction', id: 'cmp_abc', encrypted_content: 'BLOB' },+ { type: 'message', role: 'user', content: 'hi' },+ ]);+ });++ it('keeps context_compaction blobs intact too', () => {+ const body = buf({+ model: 'grok-4.5',+ input: [+ { type: 'context_compaction', id: 'cc_1', encrypted_content: 'BLOB' },+ { type: 'reasoning', encrypted_content: 'ENC' },+ ],+ });+ const out = stripEncryptedContentFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.input).toEqual([{ type: 'context_compaction', id: 'cc_1', encrypted_content: 'BLOB' }]);+ });++ it('returns null when the only encrypted_content belongs to a compaction item', () => {+ const body = buf({+ model: 'grok-4.5',+ input: [+ { type: 'compaction', id: 'cmp_abc', encrypted_content: 'BLOB' },+ { type: 'message', role: 'user', content: 'hi' },+ ],+ });+ expect(stripEncryptedContentFromBody(body)).toBeNull();+ });++ it('keeps summary-only reasoning items when nothing was stripped this round', () => {+ const body = buf({+ model: 'grok-4.5',+ input: [+ { type: 'compaction', id: 'cmp_abc' },+ { type: 'reasoning', summary: [{ type: 'summary_text', text: 's' }] },+ ],+ });+ const out = stripEncryptedContentFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ // 压缩空壳必丢;没剥过密文时,只带 summary 的 reasoning 是合法形态,保留。+ expect(parsed.input).toEqual([{ type: 'reasoning', summary: [{ type: 'summary_text', text: 's' }] }]);+ });++ it('drops a compaction shell that already arrived without its blob', () => {+ const body = buf({+ model: 'grok-4.5',+ input: [+ { type: 'compaction', id: 'cmp_abc' },+ { type: 'message', role: 'user', content: 'hi' },+ ],+ });+ const out = stripEncryptedContentFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.input).toEqual([{ type: 'message', role: 'user', content: 'hi' }]);+ });++ // codex wire: Compaction.encrypted_content 必填、ContextCompaction 可选 —— 不带密文的+ // context_compaction 是合法的可读压缩变体,不是空壳,删掉等于静默丢上下文。+ it('preserves a blob-less context_compaction (legitimate readable variant)', () => {+ const body = buf({+ model: 'grok-4.5',+ input: [+ { type: 'context_compaction', id: 'cc_1', summary: 'earlier turns' },+ { type: 'reasoning', encrypted_content: 'ENC' },+ ],+ });+ const out = stripEncryptedContentFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.input).toEqual([{ type: 'context_compaction', id: 'cc_1', summary: 'earlier turns' }]);+ });++ // 空壳判定锚在协议层顶层 input[];嵌套结构里同名的 input 数组是别人的业务数据,+ // 不能按 type 形状猜着删(删密文键仍然全树递归,那是定向删键)。+ it('does not touch nested input arrays that are not protocol history', () => {+ const body = buf({+ model: 'grok-4.5',+ input: [+ { type: 'reasoning', encrypted_content: 'ENC' },+ {+ type: 'message',+ role: 'user',+ content: 'hi',+ payload: { input: [{ type: 'compaction' }, { type: 'reasoning' }] },+ },+ ],+ });+ const out = stripEncryptedContentFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.input).toEqual([+ {+ type: 'message',+ role: 'user',+ content: 'hi',+ payload: { input: [{ type: 'compaction' }, { type: 'reasoning' }] },+ },+ ]);+ });});describe('stripToolUseProviderSpecificFieldsFromBody', () => {@@ -370,6 +488,31 @@ describe('createActiveStripTransform', () => {expect(out).toEqual({ model: 'gpt-5.5', input: [{}] });});+ // 主动剥离排在 codex-proxy transform 链首位, 跨来源压缩兼容 transform 排在其后并以+ // "encrypted_content 非空" 为触发条件。这里先把压缩 blob 剥掉, 那条兼容路径就再也+ // 认不出压缩块, 空壳会一路打到上游 → xAI 400 "Could not decode the compaction blob"。+ it('leaves the compaction blob for the downstream cross-provider transform', () => {+ const controller = createThreadStripController();+ controller.markActive('thread-a', 'grok-4.5');+ const transform = createActiveStripTransform({ controller, enabled: () => true, strip: stripEncryptedContentFromBody });++ const out = transform(+ {+ model: 'grok-4.5',+ input: [+ { type: 'compaction', id: 'cmp_abc', encrypted_content: 'BLOB' },+ { type: 'reasoning', encrypted_content: 'gAAA' },+ ],+ },+ ctx,+ );++ expect(out).toEqual({+ model: 'grok-4.5',+ input: [{ type: 'compaction', id: 'cmp_abc', encrypted_content: 'BLOB' }],+ });+ });+it('strips active thread empty thinking blocks', () => {const controller = createThreadStripController();controller.markActive('thread-a', 'claude-sonnet-4-6');diff --git a/packages/anthropic-compat-proxy/src/transform.ts b/packages/anthropic-compat-proxy/src/transform.tsindex 745bbe7dad..6073f1a75e 100644--- a/packages/anthropic-compat-proxy/src/transform.ts+++ b/packages/anthropic-compat-proxy/src/transform.ts@@ -107,9 +107,25 @@ export const stripToolUseProviderSpecificFields: RequestTransform = (body) => {return deepDeleteToolUseProviderSpecificFields(body) > 0 ? body : null;};+/**+ * Responses `input[]` 里的上下文压缩块 (OpenAI `/v1/responses/compact` 与 xAI 同名接口+ * 都回这个形态)。它的 `encrypted_content` 装的是**压缩 blob 本体** —— 压缩点之前的+ * 全部历史,不是可有可无的推理链。+ */+function isCompactionItem(node: Record<string, unknown>): boolean {+ return node.type === 'compaction' || node.type === 'context_compaction';+}+/*** 递归删除 body 里所有 `encrypted_content` 键, 返回删掉的个数。* 用于 invalid_encrypted_content 报错后的透明重试 (见 stripEncryptedContentFromBody)。+ *+ * **压缩块整块跳过**: 剥掉压缩 blob 换不回一个可用请求 —— 上游收到没有 blob 的+ * 压缩空壳会直接判 "Could not decode the compaction blob. Ensure it is unmodified+ * from the compact response." (xAI 实报, 2026-07 Grok 会话卡死)。压缩块该怎么处置+ * 由上层按目标上游决定 (codex-proxy 的跨来源压缩兼容 transform 会把读不懂的加密块+ * 换成明文占位), 而那条兼容路径正是以"encrypted_content 非空"为触发条件 —— 在这里+ * 先剥就等于把它一并绕过。*/function deepDeleteEncryptedContent(node: unknown): number {let removed = 0;@@ -118,6 +134,7 @@ function deepDeleteEncryptedContent(node: unknown): number {return removed;}if (isPlainObject(node)) {+ if (isCompactionItem(node)) return 0;if ('encrypted_content' in node) {delete node.encrypted_content;removed += 1;@@ -136,40 +153,55 @@ function isReasoningItemWithoutEncryptedContent(item: unknown): boolean {}/**- * 从 Responses-style `input[]` 丢掉"无 encrypted_content 的 reasoning"空壳。- * 只删 encrypted_content 键时,xAI 会把残留 reasoning item 判成 ModelInput 反序列化失败 (422)。+ * 缺 blob 的 `compaction` 空壳 —— 上游无法解码, 留着必 400, 只能丢。+ *+ * **只认 `compaction`, 不认 `context_compaction`**: codex wire 上 `Compaction.encrypted_content`+ * 必填、`ContextCompaction.encrypted_content` 可选 —— 后者不带密文是合法的可读压缩变体+ * (codex-proxy 的跨来源压缩兼容 transform 同样只处理带密文的项, 明文变体原样透传)。+ * 把它当空壳删掉会静默丢掉真实的压缩上下文。*/-function deepDropEmptyReasoningInputItems(node: unknown): number {- let removed = 0;- if (Array.isArray(node)) {- for (const item of node) removed += deepDropEmptyReasoningInputItems(item);- return removed;- }- if (!isPlainObject(node)) return 0;+function isCompactionShellWithoutBlob(item: unknown): boolean {+ if (!isPlainObject(item) || item.type !== 'compaction') return false;+ return typeof item.encrypted_content !== 'string' || item.encrypted_content.length === 0;+}- if (Array.isArray(node.input)) {- const kept: unknown[] = [];- for (const item of node.input) {- if (isReasoningItemWithoutEncryptedContent(item)) {- removed += 1;- continue;- }- removed += deepDropEmptyReasoningInputItems(item);- kept.push(item);- }- node.input = kept;- }+/**+ * 丢掉 Responses 请求体**协议层** `input[]` 里解不开也修不好的空壳 item:+ * - 缺 blob 的 `compaction` (**恒丢**): 本模块不再制造这种空壳+ * (见 deepDeleteEncryptedContent), 但请求体可能已经带着它进来, 兜底丢掉,+ * 别让它打到上游换一个 400;+ * - 无 encrypted_content 的 reasoning (**仅 dropReasoningShells**): 只删+ * encrypted_content 键时,xAI 会把残留 reasoning item 判成 ModelInput 反序列化失败+ * (422)。这一条只在本轮确实剥掉过密文时才做 —— 没剥过的请求里,"reasoning 只带+ * summary" 是合法形态, 不该顺手删掉。+ *+ * **只看顶层 `input`, 不递归**: Responses 请求体的协议历史只有顶层这一个 `input[]`;+ * 嵌套结构里同名的 `input` 数组(工具参数、业务对象等)不是协议历史, 按 `type` 形状+ * 猜着删会静默改坏别人的数据。删密文键可以全树递归(定向删键, 只会少发不会发错),+ * 判定"整项该不该留"必须锚在协议层。+ */+function dropEncryptedShellInputItems(body: unknown, dropReasoningShells: boolean): number {+ if (!isPlainObject(body) || !Array.isArray(body.input)) return 0;- for (const key of Object.keys(node)) {- if (key === 'input') continue;- removed += deepDropEmptyReasoningInputItems(node[key]);+ let removed = 0;+ const kept: unknown[] = [];+ for (const item of body.input) {+ if (+ isCompactionShellWithoutBlob(item) ||+ (dropReasoningShells && isReasoningItemWithoutEncryptedContent(item))+ ) {+ removed += 1;+ continue;+ }+ kept.push(item);}+ if (removed > 0) body.input = kept;return removed;}/**- * 把请求体里所有 `encrypted_content` 键递归删掉, 并丢掉因此变成空壳的 reasoning input item,- * 返回新的 Buffer。+ * 把请求体里所有 `encrypted_content` 键递归删掉 (压缩块除外), 并丢掉解不开也修不好的+ * 空壳 input item, 返回新的 Buffer。** 背景: gpt-5.5 等模型经 litellm/Azure 走 OpenAI Responses API (/v1/responses) 时,* 请求体的 reasoning item 带 `encrypted_content` (gAAA... 加密推理)。多部署负载均衡把@@ -178,9 +210,12 @@ function deepDropEmptyReasoningInputItems(node: unknown): number {* 删掉 encrypted_content 再重发即可恢复 (代价: 模型丢失上一轮的加密推理链, 可见对话保留)。* 若只删键、保留 type=reasoning 空壳,xAI 会再报 ModelInput 422 —— 所以空壳一并丢掉。*+ * **上下文压缩块除外**: 它的 encrypted_content 是压缩 blob 本体, 剥掉只会把请求变成+ * 上游无法解码的空壳 (详见 deepDeleteEncryptedContent)。+ ** 仅在 server.ts 收到该 400/422 后的"透明重试"路径调用, 正常请求不经过此函数。*- * @returns 删掉了至少一个键或空壳 → 新 Buffer; body 非 JSON / 没有该键 → null (调用方据此决定不重试)+ * @returns 删掉了至少一个键或空壳 → 新 Buffer; body 非 JSON / 无可剥内容 → null (调用方据此决定不重试)*/export function stripEncryptedContentFromBody(rawBody: Buffer): Buffer | null {let parsed: unknown;@@ -190,8 +225,11 @@ export function stripEncryptedContentFromBody(rawBody: Buffer): Buffer | null {return null;}const removedKeys = deepDeleteEncryptedContent(parsed);- if (removedKeys === 0) return null;- deepDropEmptyReasoningInputItems(parsed);+ // 空壳清理独立计数: 请求体里可能只带着一个缺 blob 的 compaction 空壳 (没有任何+ // encrypted_content 键可删), 那一样是必须处理的坏 payload, 不能因 removedKeys=0 放行。+ // 这一步只扫顶层 input[] (单次线性扫描), 不是第二遍深度遍历。+ const removedShells = dropEncryptedShellInputItems(parsed, removedKeys > 0);+ if (removedKeys === 0 && removedShells === 0) return null;try {return Buffer.from(JSON.stringify(parsed), 'utf8');} catch {