Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(proxy): compact oversized vision history before forwarding (#3606)
DavidShenXDfd99c1ba7344
diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.tsindex dba5904e92..bfe10f1294 100644--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts@@ -28,6 +28,7 @@ import {createToolUseProviderSpecificFieldsRecoveryRule,createXaiModelInputRecoveryRule,createXaiModelInputSanitizeTransform,+ compactOversizedImageHistory,dedupeDuplicateToolUseIds,repairToolExchangeAdjacency,sanitizeXaiModelInputFromBody,@@ -628,6 +629,14 @@ export async function ensureAnthropicCompatProxyReady(): Promise<void> {// 函数形态:model-access 凭据同步可能在 proxy 启动(splash)后才把 endpoint// 换成下发值;每请求现取才能保证与当前 key 同租户(proxy 内部按值 memoize)。upstream: () => claudeUpstreamEndpoint(),+ // Claude/PI 历史会把图片 base64 累积进下一次请求。仅当请求超过+ // 32 MiB 时才打开有界 ingress,并优先压缩旧的 tool_result 图片;+ // 原始媒体仍保留在媒体库,当前用户消息中的图片不被删除。+ oversizedRequestCompactor: (body, _ctx, targetBytes) =>+ typeof body === 'object' && body !== null && !Array.isArray(body)+ ? compactOversizedImageHistory(body as Record<string, unknown>, targetBytes)+ : null,+ oversizedRequestIngressBytes: 64 * 1024 * 1024,// 'oauth' 模式按 model 分流(claude-* → api.anthropic.com 走订阅;其余 → gateway 换 key)。// 'gateway' 模式恒返 null,字节级行为与扩展前一致。routingTransform: createModelRoutingTransform(),diff --git a/packages/anthropic-compat-proxy/src/index.ts b/packages/anthropic-compat-proxy/src/index.tsindex a24e7286a8..6089a64293 100644--- a/packages/anthropic-compat-proxy/src/index.ts+++ b/packages/anthropic-compat-proxy/src/index.ts@@ -42,6 +42,7 @@ export {createEncryptedContentRecoveryRule,createImageGenerationIdRecoveryRule,createToolExchangeAdjacencyRecoveryRule,+ compactOversizedImageHistory,createToolUseProviderSpecificFieldsRecoveryRule,dedupeDuplicateToolUseIds,dedupeDuplicateToolUseIdsFromBody,@@ -81,6 +82,7 @@ export type {} from './instructions-injection.js';export type {LocalRequestHandler,+ OversizedRequestCompactor,ProxyHandle,ProxyLogger,ProxyOptions,diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.tsindex 5a6369ad80..e3f6c3d4f4 100644--- a/packages/anthropic-compat-proxy/src/server.test.ts+++ b/packages/anthropic-compat-proxy/src/server.test.ts@@ -1541,7 +1541,7 @@ describe('anthropic-compat-proxy mixed sync+async transform chain', () => {upstream: custom.url,transformRequest: [// 第一个:sync transform 透传(返回 null),不改 body。- (_body) => {+ () => {order.push('sync-passthrough');return null;},@@ -2541,6 +2541,181 @@ describe('anthropic-compat-proxy request body limit(超限回可读 413,不斩expect(r.status).toBe(200);expect(gateway.bodies).toHaveLength(1);});++ it('超出硬上限但在有界 ingress 内时先压缩,压缩后正常转发', async () => {+ const gateway = await startFakeUpstream((_i, body, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ bytes: Buffer.byteLength(body, 'utf8'), body: JSON.parse(body) }));+ });+ upstreamClose = gateway.close;+ let compactorCalls = 0;+ proxy = await createAnthropicCompatProxy({+ upstream: gateway.url,+ transformRequest: [],+ maxRequestBodyBytes: 1024,+ oversizedRequestIngressBytes: 8 * 1024,+ oversizedRequestCompactor: (body) => {+ compactorCalls += 1;+ return { model: (body as Record<string, unknown>).model, compacted: true };+ },+ });+ const res = await post(proxy.url, { model: 'test-model', history: 'x'.repeat(4096) });+ expect(res.status).toBe(200);+ const json = JSON.parse(res.text) as { bytes: number; body: Record<string, unknown> };+ expect(json.body.compacted).toBe(true);+ expect(json.bytes).toBeLessThan(1024);+ expect(compactorCalls).toBe(1);+ });++ it('命中 localHandler 时同样先压缩超限 JSON,再交给 handler', async () => {+ const gateway = await startFakeUpstream((_i, _b, res) => {+ res.writeHead(500);+ res.end('local handler must prevent forwarding');+ });+ upstreamClose = gateway.close;+ let compactorCalls = 0;+ let seen: { raw: string; parsed: Record<string, unknown> } | null = null;+ proxy = await createAnthropicCompatProxy({+ upstream: gateway.url,+ transformRequest: [],+ maxRequestBodyBytes: 1024,+ oversizedRequestIngressBytes: 8 * 1024,+ oversizedRequestCompactor: (body) => {+ compactorCalls += 1;+ return { model: (body as Record<string, unknown>).model, compacted: true };+ },+ routingTransform: () => ({+ localHandler: async ({ rawBody, parsedBody, res }) => {+ seen = { raw: rawBody.toString('utf8'), parsed: parsedBody as Record<string, unknown> };+ res.writeHead(204);+ res.end();+ },+ }),+ });++ const res = await post(proxy.url, { model: 'gpt-5.5', history: 'x'.repeat(4096) });+ expect(res.status).toBe(204);+ expect(compactorCalls).toBe(1);+ expect(seen).toEqual({+ raw: JSON.stringify({ model: 'gpt-5.5', compacted: true }),+ parsed: { model: 'gpt-5.5', compacted: true },+ });+ expect(gateway.bodies).toHaveLength(0);+ });++ it('硬上限以内的请求完全跳过 oversized compactor', async () => {+ const gateway = await startFakeUpstream((_i, _body, res) => { res.writeHead(200); res.end('{}'); });+ upstreamClose = gateway.close;+ let compactorCalls = 0;+ proxy = await createAnthropicCompatProxy({+ upstream: gateway.url,+ transformRequest: [],+ maxRequestBodyBytes: 8 * 1024,+ oversizedRequestCompactor: () => {+ compactorCalls += 1;+ return null;+ },+ });+ const res = await post(proxy.url, { model: 'test-model', input: 'small' });+ expect(res.status).toBe(200);+ expect(compactorCalls).toBe(0);+ });++ it('压缩器无法安全缩小时,最终仍返回结构化 413', async () => {+ const gateway = await startFakeUpstream((_i, _body, res) => { res.writeHead(200); res.end('{}'); });+ upstreamClose = gateway.close;+ proxy = await createAnthropicCompatProxy({+ upstream: gateway.url,+ transformRequest: [],+ maxRequestBodyBytes: 1024,+ oversizedRequestIngressBytes: 8 * 1024,+ oversizedRequestCompactor: () => null,+ });+ const res = await post(proxy.url, { model: 'test-model', history: 'x'.repeat(4096) });+ expect(res.status).toBe(413);+ const json = JSON.parse(res.text) as { error: { reason: string } };+ expect(json.error.reason).toBe('request_body_too_large');+ expect(gateway.bodies).toHaveLength(0);+ });++ it('超过 ingress 上限时仍立即 413,不会把无限 body 读入内存', async () => {+ const gateway = await startFakeUpstream((_i, _body, res) => { res.writeHead(200); res.end('{}'); });+ upstreamClose = gateway.close;+ let compactorCalls = 0;+ proxy = await createAnthropicCompatProxy({+ upstream: gateway.url,+ transformRequest: [],+ maxRequestBodyBytes: 1024,+ oversizedRequestIngressBytes: 2048,+ oversizedRequestCompactor: () => {+ compactorCalls += 1;+ return null;+ },+ });+ const body = JSON.stringify({ model: 'test-model', history: 'x'.repeat(4096) });+ const res = await fetch(`${proxy.url}/v1/messages`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body,+ });+ expect(res.status).toBe(413);+ const json = await res.json() as { error: { reason: string } };+ expect(json.error.reason).toBe('request_body_too_large');+ expect(compactorCalls).toBe(0);+ expect(gateway.bodies).toHaveLength(0);+ });++ it('非法 ingress 配置不会关闭流式大小守卫', async () => {+ const gateway = await startFakeUpstream((_i, _b, res) => { res.writeHead(200); res.end('{}'); });+ upstreamClose = gateway.close;+ let compactorCalls = 0;+ proxy = await createAnthropicCompatProxy({+ upstream: gateway.url,+ transformRequest: [],+ maxRequestBodyBytes: 1024,+ oversizedRequestIngressBytes: Number.NaN,+ oversizedRequestCompactor: () => {+ compactorCalls += 1;+ return null;+ },+ });+ const body = JSON.stringify({ model: 'test-model', history: 'x'.repeat(4096) });+ const res = await fetch(`${proxy.url}/v1/messages`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body,+ });+ expect(res.status).toBe(413);+ expect(compactorCalls).toBe(0);+ expect(gateway.bodies).toHaveLength(0);+ });++ it('启用压缩器时,非 JSON 请求仍按硬上限预检', async () => {+ const gateway = await startFakeUpstream((_i, _b, res) => { res.writeHead(200); res.end('{}'); });+ upstreamClose = gateway.close;+ const warns: Array<Record<string, unknown>> = [];+ proxy = await createAnthropicCompatProxy({+ upstream: gateway.url,+ transformRequest: [],+ maxRequestBodyBytes: 1024,+ oversizedRequestIngressBytes: 8 * 1024,+ oversizedRequestCompactor: () => null,+ logger: {+ warn: (msg, ctx) => {+ if (msg === '✖ request body exceeds proxy limit → 413') warns.push(ctx ?? {});+ },+ },+ });+ const res = await fetch(`${proxy.url}/v1/messages`, {+ method: 'POST',+ headers: { 'content-type': 'text/plain' },+ body: 'x'.repeat(4096),+ });+ expect(res.status).toBe(413);+ expect(warns).toHaveLength(1);+ expect(warns[0].receivedBytes).toBe(0);+ expect(gateway.bodies).toHaveLength(0);+ });});describe('anthropic-compat-proxy 客户端中断传播', () => {diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.tsindex 9bbf4f2f5b..e9b9ee6593 100644--- a/packages/anthropic-compat-proxy/src/server.ts+++ b/packages/anthropic-compat-proxy/src/server.ts@@ -49,6 +49,7 @@ import type {RecoveryRule,RequestTransform,RequestTransformCtx,+ OversizedRequestCompactor,ResponseObserver,ResponseObserverSink,ResponseTransform,@@ -59,6 +60,9 @@ import type {// 留 32MB 给极端的长上下文 + 大附件;超出回 413,避免内存被打爆。// 调用方可用 ProxyOptions.maxRequestBodyBytes 覆盖(codex 全量重发历史的场景需要更大)。const DEFAULT_MAX_REQUEST_BODY_BYTES = 32 * 1024 * 1024;+// Oversized compaction is intentionally bounded. A request beyond this+// ingress window is rejected without buffering it into memory.+const MAX_REQUEST_INGRESS_BYTES = 64 * 1024 * 1024;// 413 响应写回后,等客户端读到响应自行断开的宽限期;超时强制 destroy 防连接悬挂。const REQUEST_TOO_LARGE_DRAIN_TIMEOUT_MS = 10 * 1000;@@ -621,6 +625,7 @@ function respondRequestTooLarge(opts: {/** Content-Length 预检命中时的声明字节数;流式守卫命中时为 null。 */declaredBytes: number | null;receivedBytes: number;+ reason?: 'request_body_too_large';}): void {const { req, res, logger } = opts;logger.warn?.('✖ request body exceeds proxy limit → 413', {@@ -635,6 +640,7 @@ function respondRequestTooLarge(opts: {const payload = Buffer.from(JSON.stringify({error: {type: 'proxy_error',+ reason: opts.reason ?? 'request_body_too_large',message: `request body too large: ${opts.declaredBytes ?? `>${opts.receivedBytes}`} bytes exceeds proxy limit of ${opts.limitBytes} bytes`,},}));@@ -682,16 +688,19 @@ async function runTransforms(transforms: RequestTransform[],ctx: RequestTransformCtx,logger: ProxyLogger,+ preParsed?: unknown,): Promise<Buffer | null> {if (transforms.length === 0) return null;if (!contentType.toLowerCase().startsWith('application/json')) return null;- let parsed: unknown;- try {- parsed = JSON.parse(rawBody.toString('utf8'));- } catch (err) {- logger.warn?.('json parse failed, falling back to passthrough', { err: String(err) });- return null;+ let parsed: unknown = preParsed;+ if (preParsed === undefined) {+ try {+ parsed = JSON.parse(rawBody.toString('utf8'));+ } catch (err) {+ logger.warn?.('json parse failed, falling back to passthrough', { err: String(err) });+ return null;+ }}let current: unknown = parsed;@@ -1636,6 +1645,28 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Prconst logger = opts.logger ?? {};const host = opts.host ?? '127.0.0.1';const maxBodyBytes = opts.maxRequestBodyBytes ?? DEFAULT_MAX_REQUEST_BODY_BYTES;+ const oversizedRequestCompactor: OversizedRequestCompactor | undefined = opts.oversizedRequestCompactor;+ // Treat a malformed ingress override as unset. Letting NaN reach the+ // stream guard would make `total > NaN` false forever and turn the bounded+ // ingress into an unbounded read.+ const configuredOversizedIngressBytes = opts.oversizedRequestIngressBytes;+ const oversizedIngressOverride =+ typeof configuredOversizedIngressBytes === 'number'+ && Number.isFinite(configuredOversizedIngressBytes)+ && configuredOversizedIngressBytes > 0+ ? configuredOversizedIngressBytes+ : undefined;+ const oversizedIngressBytes = oversizedRequestCompactor+ ? maxBodyBytes >= MAX_REQUEST_INGRESS_BYTES+ ? maxBodyBytes+ : Math.max(+ maxBodyBytes,+ Math.min(+ MAX_REQUEST_INGRESS_BYTES,+ oversizedIngressOverride ?? maxBodyBytes * 2,+ ),+ )+ : maxBodyBytes;// 入站请求 body dump 默认关(仅显式诊断时开):高并发下 64KiB×每请求的日志// 构造/落盘/终端镜像会占满宿主 main event loop,详见 ProxyOptions 注释。const dumpRequestBody = opts.debugDumpRequestBody === true;@@ -1791,6 +1822,13 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Prconst requestCtx: RequestTransformCtx = { reqId, method, url, headers };const threadId = selectedHeaderValue(headers, STABLE_THREAD_ID_HEADERS) ?? '';const contentType = headers['content-type'] ?? '';+ // The compactor only understands JSON request histories. Keep the normal+ // hard limit for other media types so enabling it cannot accidentally make+ // binary/form uploads consume the larger ingress window.+ const requestIngressBytes =+ oversizedRequestCompactor && contentType.toLowerCase().startsWith('application/json')+ ? oversizedIngressBytes+ : maxBodyBytes;// 非 POST / 没 body(GET / HEAD / DELETE 等)→ 不收集 stream,但仍跑一次路由决策:// 这类请求没有 body,routingTransform 以 `undefined` body 调用,可据 method/url/headers 路由@@ -1858,7 +1896,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr// 只有 chunked 上传才落到 collectRequestBody 的流式守卫)。// 注意读原始 req.headers —— flattenRequestHeaders 会剥掉 content-length(转发时重算)。const declaredBytes = Number(req.headers['content-length'] ?? '');- if (Number.isFinite(declaredBytes) && declaredBytes > maxBodyBytes) {+ if (Number.isFinite(declaredBytes) && declaredBytes > requestIngressBytes) {respondRequestTooLarge({req, res, logger, reqId, method, url, headers,limitBytes: maxBodyBytes,@@ -1870,7 +1908,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Prlet rawBody: Buffer;try {- rawBody = await collectRequestBody(req, maxBodyBytes);+ rawBody = await collectRequestBody(req, requestIngressBytes);} catch (err) {const msg = err instanceof Error ? err.message : String(err);if (msg === 'REQUEST_TOO_LARGE') {@@ -1917,19 +1955,77 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr// 本地 handler 命中:不转发上游、不跑 transform 链,由 handler 直接消费(协议翻译场景)。// parsedBody 复用路由阶段的解析结果,不二次 parse。if (decision?.localHandler) {+ // PI native subscription handlers also receive provider-native JSON and+ // can carry the same accumulated vision history as forwarded requests.+ // Apply the bounded compactor before the local-handler hard-limit check;+ // non-JSON or unparseable bodies still retain the historical 413 path.+ let localRawBody = rawBody;+ let localParsedBody = rawParsed;+ if (rawBody.length > maxBodyBytes && oversizedRequestCompactor) {+ const originalLocalBodyBytes = rawBody.length;+ const compactStartedAt = Date.now();+ let oversizedParsed: unknown = rawParsed;+ if (oversizedParsed === undefined && contentType.toLowerCase().startsWith('application/json')) {+ try {+ oversizedParsed = JSON.parse(rawBody.toString('utf8'));+ } catch {+ oversizedParsed = undefined;+ }+ }+ if (oversizedParsed !== undefined) {+ try {+ const compacted = oversizedRequestCompactor(oversizedParsed, requestCtx, maxBodyBytes);+ const compactedBody = isPromiseLike<unknown | null>(compacted)+ ? await compacted+ : compacted;+ if (compactedBody !== null && compactedBody !== undefined) {+ const serialized = JSON.stringify(compactedBody);+ if (typeof serialized !== 'string') throw new Error('compactor returned a non-serializable body');+ localRawBody = Buffer.from(serialized, 'utf8');+ // Do not retain the original oversized Buffer through local+ // handler execution; compaction already produced the bytes the+ // handler will consume.+ rawBody = localRawBody;+ localParsedBody = compactedBody;+ logger.info?.('oversized request body compacted before local dispatch', {+ reqId,+ originalBytes: originalLocalBodyBytes,+ compactedBytes: localRawBody.length,+ compactionMs: Date.now() - compactStartedAt,+ });+ }+ } catch (err) {+ logger.warn?.('oversized request compactor failed; enforcing hard limit', {+ reqId,+ originalBytes: originalLocalBodyBytes,+ compactionMs: Date.now() - compactStartedAt,+ err: String(err),+ });+ }+ }+ }+ if (localRawBody.length > maxBodyBytes) {+ respondRequestTooLarge({+ req, res, logger, reqId, method, url, headers,+ limitBytes: maxBodyBytes,+ declaredBytes: Number.isFinite(declaredBytes) ? declaredBytes : null,+ receivedBytes: localRawBody.length,+ });+ return;+ }if (logger.isDebugEnabled?.()) {logger.debug?.('▶ inbound request from client', {reqId,method,upstreamBase: 'local-handler',url,- bytes: rawBody.length,- ...(dumpRequestBody ? { body: dumpBody(rawBody, DEBUG_REQUEST_DUMP_MAX_BYTES) } : {}),+ bytes: localRawBody.length,+ ...(dumpRequestBody ? { body: dumpBody(localRawBody, DEBUG_REQUEST_DUMP_MAX_BYTES) } : {}),});}await runLocalHandler(decision.localHandler,- { rawBody, parsedBody: rawParsed, ctx: requestCtx, res },+ { rawBody: localRawBody, parsedBody: localParsedBody, ctx: requestCtx, res },logger,reqId,);@@ -1958,9 +2054,63 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr...requestCtx,upstreamBase: formatUpstreamBase(route.target),};+ const originalRawBodyBytes = rawBody.length;+ let bodyForTransforms = rawBody;+ let parsedForTransforms: unknown = undefined;+ if (rawBody.length > maxBodyBytes && oversizedRequestCompactor) {+ const compactStartedAt = Date.now();+ let oversizedParsed: unknown = rawParsed;+ if (oversizedParsed === undefined && contentType.toLowerCase().startsWith('application/json')) {+ try {+ oversizedParsed = JSON.parse(rawBody.toString('utf8'));+ } catch {+ oversizedParsed = undefined;+ }+ }+ if (oversizedParsed !== undefined) {+ // Reuse the parsed object even when the image compactor is a no-op;+ // this avoids a second JSON.parse for the regular transform chain.+ parsedForTransforms = oversizedParsed;+ try {+ const compacted = oversizedRequestCompactor(oversizedParsed, transformCtx, maxBodyBytes);+ const compactedBody = isPromiseLike<unknown | null>(compacted)+ ? await compacted+ : compacted;+ if (compactedBody !== null && compactedBody !== undefined) {+ const serialized = JSON.stringify(compactedBody);+ if (typeof serialized !== 'string') throw new Error('compactor returned a non-serializable body');+ bodyForTransforms = Buffer.from(serialized, 'utf8');+ parsedForTransforms = compactedBody;+ // No later stage needs the pre-compaction bytes. Releasing that+ // reference avoids retaining two large Buffers through forwarding.+ rawBody = bodyForTransforms;+ logger.info?.('oversized request body compacted before forwarding', {+ reqId,+ originalBytes: originalRawBodyBytes,+ compactedBytes: bodyForTransforms.length,+ compactionMs: Date.now() - compactStartedAt,+ });+ }+ } catch (err) {+ logger.warn?.('oversized request compactor failed; enforcing hard limit', {+ reqId,+ originalBytes: originalRawBodyBytes,+ compactionMs: Date.now() - compactStartedAt,+ err: String(err),+ });+ }+ }+ }let transformed: Buffer | null;try {- transformed = await runTransforms(rawBody, contentType, transforms, transformCtx, logger);+ transformed = await runTransforms(+ bodyForTransforms,+ contentType,+ transforms,+ transformCtx,+ logger,+ parsedForTransforms,+ );} catch (err) {transformsCompleted = true;notifyTransformSettlement();@@ -1976,9 +2126,18 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr}transformsCompleted = true;notifyTransformSettlement();- const outBody = transformed ?? rawBody;+ const outBody = transformed ?? bodyForTransforms;+ if (outBody.length > maxBodyBytes) {+ respondRequestTooLarge({+ req, res, logger, reqId, method, url, headers,+ limitBytes: maxBodyBytes,+ declaredBytes: Number.isFinite(declaredBytes) ? declaredBytes : null,+ receivedBytes: outBody.length,+ });+ return;+ }- let parsedForRewrite: unknown = rawParsed;+ let parsedForRewrite: unknown = rawParsed ?? parsedForTransforms;if (parsedForRewrite === undefined && contentType.toLowerCase().startsWith('application/json')) {try {parsedForRewrite = JSON.parse(rawBody.toString('utf8'));@@ -2039,7 +2198,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<PrreqId,method,url,- originalBytes: rawBody.length,+ originalBytes: originalRawBodyBytes,outBytes: outBody.length,});}diff --git a/packages/anthropic-compat-proxy/src/transform.test.ts b/packages/anthropic-compat-proxy/src/transform.test.tsindex 2b24254588..5289d127d0 100644--- a/packages/anthropic-compat-proxy/src/transform.test.ts+++ b/packages/anthropic-compat-proxy/src/transform.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import { createThreadStripController } from './thread-strip-controller.js';import {+ compactOversizedImageHistory,createActiveStripTransform,createDuplicateToolUseIdRecoveryRule,createEmptyAssistantMessageRecoveryRule,@@ -38,6 +39,159 @@ const ctx: RequestTransformCtx = {headers: { 'thread-id': 'thread-a' },};+describe('compactOversizedImageHistory', () => {+ it('drops older history images before the newest tool-result and newest user image', () => {+ const body = {+ model: 'claude-test',+ messages: [+ {+ role: 'assistant',+ content: [{ type: 'tool_result', content: [{ type: 'image', source: { type: 'base64', data: 'a'.repeat(4000) } }] }],+ },+ {+ role: 'assistant',+ content: [{ type: 'image', source: { type: 'base64', data: 'b'.repeat(3000) } }],+ },+ {+ role: 'user',+ content: [{ type: 'text', text: 'inspect this' }, { type: 'image', source: { type: 'base64', data: 'c'.repeat(3000) } }],+ },+ ],+ } as Record<string, unknown>;+ const originalBytes = Buffer.byteLength(JSON.stringify(body), 'utf8');+ const compacted = compactOversizedImageHistory(body, originalBytes - 2500);+ expect(compacted).toBe(body);+ const messages = body.messages as Array<Record<string, unknown>>;+ const oldToolContent = (messages[0].content as Array<Record<string, unknown>>)[0];+ expect((oldToolContent.content as Array<Record<string, unknown>>)[0].type).toBe('image');+ expect((messages[1].content as Array<Record<string, unknown>>)[0].type).toBe('text');+ expect((messages[2].content as Array<Record<string, unknown>>)[1].type).toBe('image');+ });++ it('preserves the current prompt image when a trailing tool_result also has role user', () => {+ const body = {+ model: 'claude-test',+ messages: [+ {+ role: 'user',+ content: [+ { type: 'text', text: 'continue inspecting the image' },+ { type: 'image', source: { type: 'base64', data: 'prompt-image'.repeat(500) } },+ ],+ },+ {+ role: 'assistant',+ content: [{ type: 'tool_use', id: 'tool-1', name: 'inspect', input: {} }],+ },+ {+ role: 'user',+ content: [{+ type: 'tool_result',+ tool_use_id: 'tool-1',+ content: [{ type: 'image', source: { type: 'base64', data: 'tool-image'.repeat(500) } }],+ }],+ },+ ],+ } as Record<string, unknown>;+ const bytes = Buffer.byteLength(JSON.stringify(body), 'utf8');+ compactOversizedImageHistory(body, bytes - 2_500);+ const messages = body.messages as Array<Record<string, unknown>>;+ const promptContent = messages[0].content as Array<Record<string, unknown>>;+ const toolResult = (messages[2].content as Array<Record<string, unknown>>)[0];+ expect(promptContent[1].type).toBe('image');+ expect((toolResult.content as Array<Record<string, unknown>>)[0].type).toBe('text');+ });++ it('preserves the newest image across multiple tool_result blocks in one message', () => {+ const body = {+ model: 'claude-test',+ messages: [+ {+ role: 'user',+ content: [+ { type: 'tool_result', tool_use_id: 'tool-1', content: [{ type: 'image', source: { type: 'base64', data: 'older'.repeat(1000) } }] },+ { type: 'tool_result', tool_use_id: 'tool-2', content: [{ type: 'image', source: { type: 'base64', data: 'newest'.repeat(1000) } }] },+ ],+ },+ ],+ } as Record<string, unknown>;+ const bytes = Buffer.byteLength(JSON.stringify(body), 'utf8');+ compactOversizedImageHistory(body, bytes - 2_500);+ const content = (body.messages as Array<Record<string, unknown>>)[0].content as Array<Record<string, unknown>>;+ expect((content[0].content as Array<Record<string, unknown>>)[0]).toMatchObject({ type: 'text' });+ expect((content[1].content as Array<Record<string, unknown>>)[0]).toMatchObject({ type: 'image' });+ });++ it('fails closed when the only image is in the current user message', () => {+ const body = {+ model: 'claude-test',+ messages: [{ role: 'user', content: [{ type: 'image', source: { type: 'base64', data: 'x'.repeat(5000) } }] }],+ } as Record<string, unknown>;+ const bytes = Buffer.byteLength(JSON.stringify(body), 'utf8');+ expect(compactOversizedImageHistory(body, bytes - 1)).toBeNull();+ });++ it('handles Responses input_image history and keeps the newest user item', () => {+ const body = {+ model: 'gpt-5.5',+ input: [+ { type: 'message', role: 'user', content: [{ type: 'input_image', image_url: `data:image/png;base64,${'a'.repeat(4000)}` }] },+ { type: 'message', role: 'user', content: [{ type: 'input_image', image_url: `data:image/png;base64,${'b'.repeat(4000)}` }] },+ ],+ } as Record<string, unknown>;+ const bytes = Buffer.byteLength(JSON.stringify(body), 'utf8');+ compactOversizedImageHistory(body, bytes - 2500);+ const input = body.input as Array<Record<string, unknown>>;+ expect((input[0].content as Array<Record<string, unknown>>)[0].type).toBe('input_text');+ expect((input[1].content as Array<Record<string, unknown>>)[0].type).toBe('input_image');+ });++ it('recognizes a type-less Responses user item as the current prompt', () => {+ const body = {+ model: 'gpt-5.5',+ input: [+ { type: 'message', role: 'user', content: [{ type: 'input_image', image_url: `data:image/png;base64,${'a'.repeat(4000)}` }] },+ { role: 'user', content: [{ type: 'input_image', image_url: `data:image/png;base64,${'b'.repeat(4000)}` }] },+ ],+ } as Record<string, unknown>;+ const bytes = Buffer.byteLength(JSON.stringify(body), 'utf8');+ compactOversizedImageHistory(body, bytes - 2500);+ const input = body.input as Array<Record<string, unknown>>;+ expect((input[0].content as Array<Record<string, unknown>>)[0].type).toBe('input_text');+ expect((input[1].content as Array<Record<string, unknown>>)[0].type).toBe('input_image');+ });++ it('compacts older OpenAI Chat image_url blocks while keeping the newest user images', () => {+ const body = {+ model: 'grok-4',+ messages: [+ {+ role: 'user',+ content: [+ { type: 'text', text: 'old image' },+ { type: 'image_url', image_url: { url: `data:image/png;base64,${'a'.repeat(4000)}` } },+ ],+ },+ { role: 'assistant', content: 'not the current prompt' },+ {+ role: 'user',+ content: [+ { type: 'text', text: 'inspect the latest image' },+ { type: 'image_url', image_url: { url: `data:image/png;base64,${'b'.repeat(4000)}` } },+ ],+ },+ ],+ } as Record<string, unknown>;+ const bytes = Buffer.byteLength(JSON.stringify(body), 'utf8');+ compactOversizedImageHistory(body, bytes - 2500);+ const messages = body.messages as Array<Record<string, unknown>>;+ const oldContent = messages[0].content as Array<Record<string, unknown>>;+ const currentContent = messages[2].content as Array<Record<string, unknown>>;+ expect(oldContent[1].type).toBe('text');+ expect(currentContent[1].type).toBe('image_url');+ });+});+describe('stripEncryptedContentFromBody', () => {it('drops ciphertext from intermediate agent messages while preserving readable progress and completion', () => {const body = buf({diff --git a/packages/anthropic-compat-proxy/src/transform.ts b/packages/anthropic-compat-proxy/src/transform.tsindex aeca43f418..bb37b4eb96 100644--- a/packages/anthropic-compat-proxy/src/transform.ts+++ b/packages/anthropic-compat-proxy/src/transform.ts@@ -11,6 +11,8 @@* 留证据。不要凭"它跟 gpt-5.4 应该一样" 之类的推测扩。*/+import { Buffer } from 'node:buffer';+import { DEFAULT_THREAD_ID_HEADERS, selectedHeaderValue } from './headers.js';import type { ThreadStripController } from './thread-strip-controller.js';import type { RecoveryRule, RequestTransform, RequestTransformCtx } from './types.js';@@ -1155,6 +1157,227 @@ export function replaceToolResultImagesWithNotice(return { ...body, messages: nextMessages };}+/**+ * Compact image-heavy conversation history for a request that already crossed+ * the proxy's hard body limit.+ *+ * This is deliberately a synchronous, local-only pass. The newest user+ * message is kept intact so the current prompt/image is never silently+ * removed. Older history images are dropped before the newest tool-result+ * image, with the current prompt always protected. The original media+ * remains in the media library; the+ * request-local replacement is only a small, explicit text notice.+ *+ * The function mutates the parsed request object in place (the proxy has+ * already paid the JSON.parse cost for an oversized request) and returns it+ * only when at least one image was replaced. `targetBytes` is used as a+ * cheap estimate while selecting candidates; the proxy performs the final+ * serialized-byte check after all regular transforms have run.+ */+const OVERSIZED_IMAGE_OMITTED_TEXT =+ '[Earlier image omitted to keep this request within the provider size limit. '+ + 'Do not infer its contents; ask the user to resend it if it is needed.]';++interface OversizedImageCandidate {+ container: unknown[];+ index: number;+ replacement: Record<string, string>;+ /** 0 = old tool-result, 1 = other history, 2 = newest tool-result. */+ priority: number;+ /** Older messages are removed before newer messages. */+ age: number;+}++function jsonByteLength(value: unknown): number {+ return Buffer.byteLength(JSON.stringify(value), 'utf8');+}++function collectOversizedAnthropicImages(+ messages: unknown[],+ candidates: OversizedImageCandidate[],+): void {+ let newestToolResultCandidateIndex = -1;+ let latestUserIndex = -1;+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ const message = messages[i];+ if (!isPlainObject(message) || message.role !== 'user') continue;+ // Anthropic represents tool results as `role: user` messages too. A+ // trailing tool_result therefore must not hide the actual prompt message+ // whose images are still part of the current turn. Treat a user message+ // as a prompt when it has any non-tool_result block (plain text content is+ // a prompt as well); tool_result-only messages remain compactable history.+ const content = message.content;+ const isPrompt = !Array.isArray(content)+ || content.some((block) => !isPlainObject(block) || block.type !== 'tool_result');+ if (isPrompt) {+ latestUserIndex = i;+ break;+ }+ }++ const scan = (content: unknown[], messageIndex: number, inToolResult: boolean): void => {+ for (let index = 0; index < content.length; index += 1) {+ const block = content[index];+ if (!isPlainObject(block)) continue;+ if (block.type === 'image') {+ // Preserve every image in the newest user message, including images+ // nested in its tool_result content.+ if (messageIndex === latestUserIndex) continue;+ const candidate: OversizedImageCandidate = {+ container: content,+ index,+ replacement: { type: 'text', text: OVERSIZED_IMAGE_OMITTED_TEXT },+ priority: inToolResult ? 0 : 1,+ age: messageIndex,+ };+ candidates.push(candidate);+ if (+ inToolResult+ && (+ newestToolResultCandidateIndex < 0+ // `index` is local to each nested content array, so it cannot+ // order images from separate tool_result blocks in one message.+ // Candidates are collected in wire order; the later candidate is+ // the newer image when message ages tie.+ || candidate.age >= candidates[newestToolResultCandidateIndex].age+ )+ ) {+ newestToolResultCandidateIndex = candidates.length - 1;+ }+ continue;+ }+ if (block.type === 'tool_result' && Array.isArray(block.content)) {+ scan(block.content, messageIndex, true);+ }+ }+ };++ for (let messageIndex = 0; messageIndex < messages.length; messageIndex += 1) {+ const message = messages[messageIndex];+ if (!isPlainObject(message) || !Array.isArray(message.content)) continue;+ scan(message.content, messageIndex, false);+ }+ // Keep the most recent tool-result image behind older history images. It+ // may still be removed as a last resort when no other candidate can bring+ // the request under the hard limit, but it is never the first image dropped+ // merely because tool results use role=user in Anthropic's wire format.+ if (newestToolResultCandidateIndex >= 0) {+ candidates[newestToolResultCandidateIndex].priority = 2;+ }+}++function isResponsesUserMessage(item: Record<string, unknown>): boolean {+ // Responses clients in the wild omit `type` for ordinary user messages;+ // explicit non-message item types must remain ineligible for protection.+ return item.role === 'user' && (item.type === 'message' || item.type === undefined);+}++function collectOversizedOpenAiChatImages(+ messages: unknown[],+ candidates: OversizedImageCandidate[],+): void {+ let latestUserIndex = -1;+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ const message = messages[i];+ if (isPlainObject(message) && message.role === 'user') {+ latestUserIndex = i;+ break;+ }+ }++ for (let messageIndex = 0; messageIndex < messages.length; messageIndex += 1) {+ const message = messages[messageIndex];+ if (!isPlainObject(message) || !Array.isArray(message.content)) continue;+ for (let index = 0; index < message.content.length; index += 1) {+ const block = message.content[index];+ if (!isPlainObject(block) || block.type !== 'image_url') continue;+ // OpenAI Chat uses a normal role=user message for the current prompt;+ // keep every image in that newest user message intact.+ if (messageIndex === latestUserIndex) continue;+ candidates.push({+ container: message.content,+ index,+ replacement: { type: 'text', text: OVERSIZED_IMAGE_OMITTED_TEXT },+ priority: 1,+ age: messageIndex,+ });+ }+ }+}++function collectOversizedResponsesImages(+ input: unknown[],+ candidates: OversizedImageCandidate[],+): void {+ let latestUserIndex = -1;+ for (let i = input.length - 1; i >= 0; i -= 1) {+ const item = input[i];+ if (isPlainObject(item) && isResponsesUserMessage(item)) {+ latestUserIndex = i;+ break;+ }+ }++ for (let itemIndex = 0; itemIndex < input.length; itemIndex += 1) {+ const item = input[itemIndex];+ if (!isPlainObject(item)) continue;+ const content = Array.isArray(item.content) ? item.content : null;+ if (!content) continue;+ for (let index = 0; index < content.length; index += 1) {+ const block = content[index];+ if (!isPlainObject(block) || block.type !== 'input_image') continue;+ if (itemIndex === latestUserIndex) continue;+ candidates.push({+ container: content,+ index,+ replacement: { type: 'input_text', text: OVERSIZED_IMAGE_OMITTED_TEXT },+ priority: 1,+ age: itemIndex,+ });+ }+ }+}++export function compactOversizedImageHistory(+ body: Record<string, unknown>,+ targetBytes: number,+): Record<string, unknown> | null {+ if (!Number.isFinite(targetBytes) || targetBytes <= 0) return null;++ const candidates: OversizedImageCandidate[] = [];+ if (Array.isArray(body.messages)) {+ collectOversizedAnthropicImages(body.messages, candidates);+ collectOversizedOpenAiChatImages(body.messages, candidates);+ }+ if (Array.isArray(body.input)) {+ collectOversizedResponsesImages(body.input, candidates);+ }+ // Avoid serializing a potentially huge text-only history: the common+ // oversized-text case has no safe image candidate to compact.+ if (candidates.length === 0) return null;++ let estimatedBytes: number;+ try {+ estimatedBytes = jsonByteLength(body);+ } catch {+ return null;+ }+ if (estimatedBytes <= targetBytes) return null;++ candidates.sort((a, b) => a.priority - b.priority || a.age - b.age);+ let replaced = 0;+ for (const candidate of candidates) {+ const previousBytes = jsonByteLength(candidate.container[candidate.index]);+ const replacementBytes = jsonByteLength(candidate.replacement);+ candidate.container[candidate.index] = candidate.replacement;+ estimatedBytes += replacementBytes - previousBytes;+ replaced += 1;+ if (estimatedBytes <= targetBytes) break;+ }++ return replaced > 0 ? body : null;+}+/** glm-5.2 (智谱,官方仅文本/代码模态) —— 直通与网关两条路由同一 model id。 */const stripGlm52: ModelStripHandler = (body) => replaceToolResultImagesWithNotice(body);diff --git a/packages/anthropic-compat-proxy/src/types.ts b/packages/anthropic-compat-proxy/src/types.tsindex 0bb3354eb0..91ebfc306c 100644--- a/packages/anthropic-compat-proxy/src/types.ts+++ b/packages/anthropic-compat-proxy/src/types.ts@@ -63,6 +63,21 @@ export interface RequestTransform {onRequestSettled?: (requestId: number) => void;}+/**+ * A bounded, request-local compactor used only when the inbound body is over+ * the normal forwarding limit. It must be deterministic and must not perform+ * network or filesystem I/O. Returning null means that no safe compaction was+ * possible; the regular transform chain still gets a chance to reduce the+ * body, after which the hard limit is enforced.+ */+export interface OversizedRequestCompactor {+ (+ body: unknown,+ ctx: RequestTransformCtx,+ targetBytes: number,+ ): unknown | null | Promise<unknown | null>;+}+/*** 本地 handler —— 路由决策命中 `localHandler` 时,代理**不转发上游**,由 handler 直接消费* 请求并把响应写回 `res`(典型:协议翻译,如 Anthropic Messages ↔ OpenAI Responses)。@@ -269,6 +284,17 @@ export interface ProxyOptions {* 注意: body 会整段缓冲进内存并 JSON.parse,该值同时就是单请求的内存 / 解析停顿预算。*/maxRequestBodyBytes?: number;+ /**+ * Optional compactor for bodies that exceed maxRequestBodyBytes. Enabling+ * this also permits a bounded ingress window so the compactor can inspect a+ * request before the hard limit is applied. Requests within the normal+ * limit do not enter this path. When routing selects a local handler, the+ * same compaction result is passed to that handler before its hard-limit+ * check.+ */+ oversizedRequestCompactor?: OversizedRequestCompactor;+ /** Maximum bytes accepted for an oversized request before compaction. */+ oversizedRequestIngressBytes?: number;/*** 可选: 出站(上游方向)代理解析器。per-request 以最终上游 origin 现取:* - `http://` 代理地址 = 经该代理转发(https 上游走 CONNECT 隧道、http 上游走绝对形式)diff --git a/scripts/__tests__/ensure-agent-binaries.test.mjs b/scripts/__tests__/ensure-agent-binaries.test.mjsindex c15783fc53..d32b08fa1c 100644--- a/scripts/__tests__/ensure-agent-binaries.test.mjs+++ b/scripts/__tests__/ensure-agent-binaries.test.mjs@@ -101,6 +101,22 @@ test('isValidDirDist: requires the manifest and every sidecar asset, not just thassert.equal(isValidDirDist(dir, binPath), false);});+test('isValidDirDist: required runtime assets must also be present', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ensure-dirdist-required-'));+ const binPath = path.join(dir, 'pi');+ fs.writeFileSync(binPath, Buffer.alloc(4096, 1));+ fs.mkdirSync(path.join(dir, 'theme'));+ for (const name of ['dark.json', 'light.json', 'theme-schema.json']) {+ fs.writeFileSync(path.join(dir, 'theme', name), '{}');+ }+ writeDirDistManifest(dir);++ const required = ['theme/dark.json', 'theme/light.json', 'theme/theme-schema.json'];+ assert.equal(isValidDirDist(dir, binPath, required), true);+ fs.rmSync(path.join(dir, 'theme', 'light.json'));+ assert.equal(isValidDirDist(dir, binPath, required), false);+});+test('verifyDirDistManifest: rejects size drift, empty manifests, and malformed entries', () => {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ensure-dirdist-verify-'));fs.writeFileSync(path.join(dir, 'pi'), Buffer.alloc(4096, 1));diff --git a/scripts/__tests__/pi-update-layout.test.mjs b/scripts/__tests__/pi-update-layout.test.mjsindex 6565813308..d5c261ba05 100644--- a/scripts/__tests__/pi-update-layout.test.mjs+++ b/scripts/__tests__/pi-update-layout.test.mjs@@ -8,8 +8,10 @@ import test from 'node:test';import {assertPinnedRuntimeAsset,assetDigestMatchesUpstream,+ ensurePiThemeAssets,extractArchive,flattenExtractedDir,+ hasPiThemeAssets,readCachedAssetDigest,} from '../../tools/pi/update.mjs';@@ -39,6 +41,19 @@ test('Pi updater still flattens the nested Unix release layout', (t) => {assert.ok(fs.statSync(path.join(dir, 'theme')).isDirectory());});+test('Pi updater supplies fallback themes when an archive omits them', () => {+ const dir = tempDir();+ assert.equal(hasPiThemeAssets(dir), false);+ ensurePiThemeAssets(dir);+ assert.equal(hasPiThemeAssets(dir), true);+ assert.equal(JSON.parse(fs.readFileSync(path.join(dir, 'theme', 'dark.json'), 'utf8')).name, 'dark');+ assert.equal(JSON.parse(fs.readFileSync(path.join(dir, 'theme', 'light.json'), 'utf8')).name, 'light');++ fs.writeFileSync(path.join(dir, 'theme', 'dark.json'), '{"name":"custom"}');+ ensurePiThemeAssets(dir);+ assert.equal(JSON.parse(fs.readFileSync(path.join(dir, 'theme', 'dark.json'), 'utf8')).name, 'custom');+});+test('Pi updater extracts tar.gz archives streamed to the system tar', async (t) => {const root = tempDir();t.after(() => fs.rmSync(root, { recursive: true, force: true }));diff --git a/scripts/ensure-agent-binaries.mjs b/scripts/ensure-agent-binaries.mjsindex 6caf1c9e37..df507c56a6 100644--- a/scripts/ensure-agent-binaries.mjs+++ b/scripts/ensure-agent-binaries.mjs@@ -33,7 +33,13 @@ const KINDS = {claude: { binDir: 'claude-code-bin', base: 'claude', module: '../tools/claude/update.mjs' },codex: { binDir: 'codex-bin', base: 'codex', module: '../tools/codex/update.mjs' },ripgrep: { binDir: 'ripgrep-bin', base: 'rg', module: '../tools/ripgrep/update.mjs' },- pi: { binDir: 'pi-bin', base: 'pi', module: '../tools/pi/update.mjs', dirDist: true },+ pi: {+ binDir: 'pi-bin',+ base: 'pi',+ module: '../tools/pi/update.mjs',+ dirDist: true,+ requiredDirDistFiles: ['theme/dark.json', 'theme/light.json', 'theme/theme-schema.json'],+ },};/**@@ -92,8 +98,18 @@ export function isValidBinary(absPath) {* theme/ 等旁侧资产时 RPC 启动即崩,只验主执行文件会把残缺目录当"已就位"跳过安装,* 随后被打进安装包(codex 报)。清单缺失(旧安装/半成品)按未就位处理,重新 promote 自愈。*/-export function isValidDirDist(binDirPath, binPath) {- return isValidBinary(binPath) && verifyDirDistManifest(binDirPath);+export function isValidDirDist(binDirPath, binPath, requiredFiles = []) {+ if (!isValidBinary(binPath) || !verifyDirDistManifest(binDirPath)) return false;+ const root = path.resolve(binDirPath);+ return requiredFiles.every((relativePath) => {+ const filePath = path.resolve(root, relativePath);+ if (filePath !== root && !filePath.startsWith(`${root}${path.sep}`)) return false;+ try {+ return fs.statSync(filePath).isFile();+ } catch {+ return false;+ }+ });}/**@@ -194,7 +210,9 @@ export async function ensureBinary(kind, platformKey = currentPlatformKey(), { f// 已就位且版本标记 == pin 才跳过;标记缺失/不匹配则刷新(promoteOnePlatform 写入标记)。// dirDist 的"已就位"额外要求安装清单齐全,不能只看主执行文件。- const presentAndValid = cfg.dirDist ? isValidDirDist(binDirPath, binPath) : isValidBinary(binPath);+ const presentAndValid = cfg.dirDist+ ? isValidDirDist(binDirPath, binPath, cfg.requiredDirDistFiles)+ : isValidBinary(binPath);if (!force && presentAndValid && readInstalledVersion(markerPath) === version) {log(`${kind} ${platformKey}: already present @ ${version}, skip`);return binPath;@@ -254,7 +272,9 @@ export async function ensureBinary(kind, platformKey = currentPlatformKey(), { f// 被占用(app 运行中、EBUSY)时只 warn 不抛,会留下旧 binary + 旧标记,这里据此把静默失败// 转成显式错误。本地复用路径同样受此终检兜底。const installed = readInstalledVersion(markerPath);- const finalValid = cfg.dirDist ? isValidDirDist(binDirPath, binPath) : isValidBinary(binPath);+ const finalValid = cfg.dirDist+ ? isValidDirDist(binDirPath, binPath, cfg.requiredDirDistFiles)+ : isValidBinary(binPath);if (!finalValid || installed !== version) {throw new Error(`${kind} ${platformKey}: ensure failed — expected ${version} at ${binPath} but installed marker is ${installed ?? '(none)'}. ` +diff --git a/tools/pi/latest.json b/tools/pi/latest.jsonindex 081f14f51e..d1c43bf603 100644--- a/tools/pi/latest.json+++ b/tools/pi/latest.json@@ -1,38 +1,38 @@{- "version": "0.84.3",- "tag_name": "v0.84.3",- "name": "v0.84.3",- "published_at": "2026-08-24T11:09:57Z",+ "version": "0.84.4",+ "tag_name": "v0.84.4",+ "name": "v0.84.4",+ "published_at": "2026-08-28T22:08:23Z","runtimeAssets": {"darwin-arm64": {- "url": "https://github.com/earendil-works/pi/releases/download/v0.84.3/pi-darwin-arm64.tar.gz",- "sha256": "0120c9f99ea05fe801e6e7c2c9d91dd65636563ca0803711b37b9f32920d4b63",- "size": 30919980+ "url": "https://github.com/earendil-works/pi/releases/download/v0.84.4/pi-darwin-arm64.tar.gz",+ "sha256": "c68e3ac4d05b4e282aaab2e6c76f161d3e9e68f19a22e38913cbfaadb6c800f0",+ "size": 30928407},"darwin-x64": {- "url": "https://github.com/earendil-works/pi/releases/download/v0.84.3/pi-darwin-x64.tar.gz",- "sha256": "b99706b3254faaf3695395ecb69cb7e1f4d4822bd3f832e6d1f2636d896b6bde",- "size": 33434213+ "url": "https://github.com/earendil-works/pi/releases/download/v0.84.4/pi-darwin-x64.tar.gz",+ "sha256": "7a042d6413065421387001a4986190a1a03186c95a695f4dee0bdc76e60de8f7",+ "size": 33440191},"linux-x64": {- "url": "https://github.com/earendil-works/pi/releases/download/v0.84.3/pi-linux-x64.tar.gz",- "sha256": "6f8bb67c21bc6b8a8a106d354f56d7fd4a190a3cd8ad3a32db45f6d281a5d008",- "size": 42458773+ "url": "https://github.com/earendil-works/pi/releases/download/v0.84.4/pi-linux-x64.tar.gz",+ "sha256": "c2f3c3e6a1850bd87654cc3ca8811013272397c3d042a4e2a64c43ee1b423972",+ "size": 42464648},"linux-arm64": {- "url": "https://github.com/earendil-works/pi/releases/download/v0.84.3/pi-linux-arm64.tar.gz",- "sha256": "e7cd48cd6f64b708e8459a890882b1007332f6e6b876fe1fd5c5203abd0addb7",- "size": 42521548+ "url": "https://github.com/earendil-works/pi/releases/download/v0.84.4/pi-linux-arm64.tar.gz",+ "sha256": "135580f6b942151646e67b8b866d987d28ce3cff5a497030775ddd29659f943d",+ "size": 42529658},"win32-x64": {- "url": "https://github.com/earendil-works/pi/releases/download/v0.84.3/pi-windows-x64.zip",- "sha256": "636a56f546c8bb1f2cb327964b7afbd9302efcd45c1704922a097cd8bd935fb9",- "size": 44900235+ "url": "https://github.com/earendil-works/pi/releases/download/v0.84.4/pi-windows-x64.zip",+ "sha256": "03b2318774f18721e959d9f8f3340a9f942e7aa516fb7030d3007a12a40a4a97",+ "size": 44907374},"win32-arm64": {- "url": "https://github.com/earendil-works/pi/releases/download/v0.84.3/pi-windows-arm64.zip",- "sha256": "d0f28a5bbeddcaee25fb7f4d8c70917d2c287d02b815614382aac9ac55a8fe39",- "size": 43448675+ "url": "https://github.com/earendil-works/pi/releases/download/v0.84.4/pi-windows-arm64.zip",+ "sha256": "6b2726efc34a9158ab06bf7b981f7bcccf15de9ea236a3f4ef7a894a78aa386e",+ "size": 43455125}}}diff --git a/tools/pi/theme/dark.json b/tools/pi/theme/dark.jsonnew file mode 100644index 0000000000..d4d504155f--- /dev/null+++ b/tools/pi/theme/dark.json@@ -0,0 +1,87 @@+{+ "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",+ "name": "dark",+ "vars": {+ "cyan": "#00d7ff",+ "blue": "#5f87ff",+ "green": "#b5bd68",+ "red": "#cc6666",+ "yellow": "#ffff00",+ "text": "#d4d4d4",+ "gray": "#808080",+ "dimGray": "#666666",+ "darkGray": "#505050",+ "accent": "#8abeb7",+ "selectedBg": "#3a3a4a",+ "userMsgBg": "#343541",+ "toolPendingBg": "#282832",+ "toolSuccessBg": "#283228",+ "toolErrorBg": "#3c2828",+ "customMsgBg": "#2d2838"+ },+ "colors": {+ "accent": "accent",+ "border": "blue",+ "borderAccent": "cyan",+ "borderMuted": "darkGray",+ "success": "green",+ "error": "red",+ "warning": "yellow",+ "muted": "gray",+ "dim": "dimGray",+ "text": "text",+ "thinkingText": "gray",++ "selectedBg": "selectedBg",+ "userMessageBg": "userMsgBg",+ "userMessageText": "text",+ "customMessageBg": "customMsgBg",+ "customMessageText": "text",+ "customMessageLabel": "#9575cd",+ "toolPendingBg": "toolPendingBg",+ "toolSuccessBg": "toolSuccessBg",+ "toolErrorBg": "toolErrorBg",+ "toolTitle": "text",+ "toolOutput": "gray",++ "mdHeading": "#f0c674",+ "mdLink": "#81a2be",+ "mdLinkUrl": "dimGray",+ "mdCode": "accent",+ "mdCodeBlock": "green",+ "mdCodeBlockBorder": "gray",+ "mdQuote": "gray",+ "mdQuoteBorder": "gray",+ "mdHr": "gray",+ "mdListBullet": "accent",++ "toolDiffAdded": "green",+ "toolDiffRemoved": "red",+ "toolDiffContext": "gray",++ "syntaxComment": "#6A9955",+ "syntaxKeyword": "#569CD6",+ "syntaxFunction": "#DCDCAA",+ "syntaxVariable": "#9CDCFE",+ "syntaxString": "#CE9178",+ "syntaxNumber": "#B5CEA8",+ "syntaxType": "#4EC9B0",+ "syntaxOperator": "#D4D4D4",+ "syntaxPunctuation": "#D4D4D4",++ "thinkingOff": "darkGray",+ "thinkingMinimal": "#6e6e6e",+ "thinkingLow": "#5f87af",+ "thinkingMedium": "#81a2be",+ "thinkingHigh": "#b294bb",+ "thinkingXhigh": "#d183e8",+ "thinkingMax": "#ff5fff",++ "bashMode": "green"+ },+ "export": {+ "pageBg": "#18181e",+ "cardBg": "#1e1e24",+ "infoBg": "#3c3728"+ }+}diff --git a/tools/pi/theme/light.json b/tools/pi/theme/light.jsonnew file mode 100644index 0000000000..ef0d5c3035--- /dev/null+++ b/tools/pi/theme/light.json@@ -0,0 +1,86 @@+{+ "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",+ "name": "light",+ "vars": {+ "teal": "#5a8080",+ "blue": "#547da7",+ "green": "#588458",+ "red": "#aa5555",+ "yellow": "#9a7326",+ "text": "#1f2328",+ "mediumGray": "#6c6c6c",+ "dimGray": "#767676",+ "lightGray": "#b0b0b0",+ "selectedBg": "#d0d0e0",+ "userMsgBg": "#e8e8e8",+ "toolPendingBg": "#e8e8f0",+ "toolSuccessBg": "#e8f0e8",+ "toolErrorBg": "#f0e8e8",+ "customMsgBg": "#ede7f6"+ },+ "colors": {+ "accent": "teal",+ "border": "blue",+ "borderAccent": "teal",+ "borderMuted": "lightGray",+ "success": "green",+ "error": "red",+ "warning": "yellow",+ "muted": "mediumGray",+ "dim": "dimGray",+ "text": "text",+ "thinkingText": "mediumGray",++ "selectedBg": "selectedBg",+ "userMessageBg": "userMsgBg",+ "userMessageText": "text",+ "customMessageBg": "customMsgBg",+ "customMessageText": "text",+ "customMessageLabel": "#7e57c2",+ "toolPendingBg": "toolPendingBg",+ "toolSuccessBg": "toolSuccessBg",+ "toolErrorBg": "toolErrorBg",+ "toolTitle": "text",+ "toolOutput": "mediumGray",++ "mdHeading": "yellow",+ "mdLink": "blue",+ "mdLinkUrl": "dimGray",+ "mdCode": "teal",+ "mdCodeBlock": "green",+ "mdCodeBlockBorder": "mediumGray",+ "mdQuote": "mediumGray",+ "mdQuoteBorder": "mediumGray",+ "mdHr": "mediumGray",+ "mdListBullet": "green",++ "toolDiffAdded": "green",+ "toolDiffRemoved": "red",+ "toolDiffContext": "mediumGray",++ "syntaxComment": "#008000",+ "syntaxKeyword": "#0000FF",+ "syntaxFunction": "#795E26",+ "syntaxVariable": "#001080",+ "syntaxString": "#A31515",+ "syntaxNumber": "#098658",+ "syntaxType": "#267F99",+ "syntaxOperator": "#000000",+ "syntaxPunctuation": "#000000",++ "thinkingOff": "lightGray",+ "thinkingMinimal": "#767676",+ "thinkingLow": "blue",+ "thinkingMedium": "teal",+ "thinkingHigh": "#875f87",+ "thinkingXhigh": "#8b008b",+ "thinkingMax": "#af005f",++ "bashMode": "green"+ },+ "export": {+ "pageBg": "#f8f8f8",+ "cardBg": "#ffffff",+ "infoBg": "#fffae6"+ }+}diff --git a/tools/pi/theme/theme-schema.json b/tools/pi/theme/theme-schema.jsonnew file mode 100644index 0000000000..4ab36a725f--- /dev/null+++ b/tools/pi/theme/theme-schema.json@@ -0,0 +1,340 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "title": "Pi Coding Agent Theme",+ "description": "Theme schema for Pi coding agent",+ "type": "object",+ "required": ["name", "colors"],+ "properties": {+ "$schema": {+ "type": "string",+ "description": "JSON schema reference"+ },+ "name": {+ "type": "string",+ "pattern": "^[^/]+$",+ "description": "Theme name. Must not contain '/' because it is reserved for automatic light/dark theme settings."+ },+ "vars": {+ "type": "object",+ "description": "Reusable color variables",+ "additionalProperties": {+ "oneOf": [+ {+ "type": "string",+ "description": "Hex color (#RRGGBB), variable reference, or empty string for terminal default"+ },+ {+ "type": "integer",+ "minimum": 0,+ "maximum": 255,+ "description": "256-color palette index (0-255)"+ }+ ]+ }+ },+ "colors": {+ "type": "object",+ "description": "Theme color definitions (thinkingMax is optional and falls back to thinkingXhigh)",+ "required": [+ "accent",+ "border",+ "borderAccent",+ "borderMuted",+ "success",+ "error",+ "warning",+ "muted",+ "dim",+ "text",+ "thinkingText",+ "selectedBg",+ "userMessageBg",+ "userMessageText",+ "customMessageBg",+ "customMessageText",+ "customMessageLabel",+ "toolPendingBg",+ "toolSuccessBg",+ "toolErrorBg",+ "toolTitle",+ "toolOutput",+ "mdHeading",+ "mdLink",+ "mdLinkUrl",+ "mdCode",+ "mdCodeBlock",+ "mdCodeBlockBorder",+ "mdQuote",+ "mdQuoteBorder",+ "mdHr",+ "mdListBullet",+ "toolDiffAdded",+ "toolDiffRemoved",+ "toolDiffContext",+ "syntaxComment",+ "syntaxKeyword",+ "syntaxFunction",+ "syntaxVariable",+ "syntaxString",+ "syntaxNumber",+ "syntaxType",+ "syntaxOperator",+ "syntaxPunctuation",+ "thinkingOff",+ "thinkingMinimal",+ "thinkingLow",+ "thinkingMedium",+ "thinkingHigh",+ "thinkingXhigh",+ "bashMode"+ ],+ "properties": {+ "accent": {+ "$ref": "#/$defs/colorValue",+ "description": "Primary accent color (logo, selected items, cursor)"+ },+ "border": {+ "$ref": "#/$defs/colorValue",+ "description": "Normal borders"+ },+ "borderAccent": {+ "$ref": "#/$defs/colorValue",+ "description": "Highlighted borders"+ },+ "borderMuted": {+ "$ref": "#/$defs/colorValue",+ "description": "Subtle borders"+ },+ "success": {+ "$ref": "#/$defs/colorValue",+ "description": "Success states"+ },+ "error": {+ "$ref": "#/$defs/colorValue",+ "description": "Error states"+ },+ "warning": {+ "$ref": "#/$defs/colorValue",+ "description": "Warning states"+ },+ "muted": {+ "$ref": "#/$defs/colorValue",+ "description": "Secondary/dimmed text"+ },+ "dim": {+ "$ref": "#/$defs/colorValue",+ "description": "Very dimmed text (more subtle than muted)"+ },+ "text": {+ "$ref": "#/$defs/colorValue",+ "description": "Default text color (usually empty string)"+ },+ "thinkingText": {+ "$ref": "#/$defs/colorValue",+ "description": "Thinking block text color"+ },+ "selectedBg": {+ "$ref": "#/$defs/colorValue",+ "description": "Selected item background"+ },+ "userMessageBg": {+ "$ref": "#/$defs/colorValue",+ "description": "User message background"+ },+ "userMessageText": {+ "$ref": "#/$defs/colorValue",+ "description": "User message text color"+ },+ "customMessageBg": {+ "$ref": "#/$defs/colorValue",+ "description": "Custom message background (hook-injected messages)"+ },+ "customMessageText": {+ "$ref": "#/$defs/colorValue",+ "description": "Custom message text color"+ },+ "customMessageLabel": {+ "$ref": "#/$defs/colorValue",+ "description": "Custom message type label color"+ },+ "toolPendingBg": {+ "$ref": "#/$defs/colorValue",+ "description": "Tool execution box (pending state)"+ },+ "toolSuccessBg": {+ "$ref": "#/$defs/colorValue",+ "description": "Tool execution box (success state)"+ },+ "toolErrorBg": {+ "$ref": "#/$defs/colorValue",+ "description": "Tool execution box (error state)"+ },+ "toolTitle": {+ "$ref": "#/$defs/colorValue",+ "description": "Tool execution box title color"+ },+ "toolOutput": {+ "$ref": "#/$defs/colorValue",+ "description": "Tool execution box output text color"+ },+ "mdHeading": {+ "$ref": "#/$defs/colorValue",+ "description": "Markdown heading text"+ },+ "mdLink": {+ "$ref": "#/$defs/colorValue",+ "description": "Markdown link text"+ },+ "mdLinkUrl": {+ "$ref": "#/$defs/colorValue",+ "description": "Markdown link URL"+ },+ "mdCode": {+ "$ref": "#/$defs/colorValue",+ "description": "Markdown inline code"+ },+ "mdCodeBlock": {+ "$ref": "#/$defs/colorValue",+ "description": "Markdown code block content"+ },+ "mdCodeBlockBorder": {+ "$ref": "#/$defs/colorValue",+ "description": "Markdown code block fences"+ },+ "mdQuote": {+ "$ref": "#/$defs/colorValue",+ "description": "Markdown blockquote text"+ },+ "mdQuoteBorder": {+ "$ref": "#/$defs/colorValue",+ "description": "Markdown blockquote border"+ },+ "mdHr": {+ "$ref": "#/$defs/colorValue",+ "description": "Markdown horizontal rule"+ },+ "mdListBullet": {+ "$ref": "#/$defs/colorValue",+ "description": "Markdown list bullets/numbers"+ },+ "toolDiffAdded": {+ "$ref": "#/$defs/colorValue",+ "description": "Added lines in tool diffs"+ },+ "toolDiffRemoved": {+ "$ref": "#/$defs/colorValue",+ "description": "Removed lines in tool diffs"+ },+ "toolDiffContext": {+ "$ref": "#/$defs/colorValue",+ "description": "Context lines in tool diffs"+ },+ "syntaxComment": {+ "$ref": "#/$defs/colorValue",+ "description": "Syntax highlighting: comments"+ },+ "syntaxKeyword": {+ "$ref": "#/$defs/colorValue",+ "description": "Syntax highlighting: keywords"+ },+ "syntaxFunction": {+ "$ref": "#/$defs/colorValue",+ "description": "Syntax highlighting: function names"+ },+ "syntaxVariable": {+ "$ref": "#/$defs/colorValue",+ "description": "Syntax highlighting: variable names"+ },+ "syntaxString": {+ "$ref": "#/$defs/colorValue",+ "description": "Syntax highlighting: string literals"+ },+ "syntaxNumber": {+ "$ref": "#/$defs/colorValue",+ "description": "Syntax highlighting: number literals"+ },+ "syntaxType": {+ "$ref": "#/$defs/colorValue",+ "description": "Syntax highlighting: type names"+ },+ "syntaxOperator": {+ "$ref": "#/$defs/colorValue",+ "description": "Syntax highlighting: operators"+ },+ "syntaxPunctuation": {+ "$ref": "#/$defs/colorValue",+ "description": "Syntax highlighting: punctuation"+ },+ "thinkingOff": {+ "$ref": "#/$defs/colorValue",+ "description": "Thinking level border: off"+ },+ "thinkingMinimal": {+ "$ref": "#/$defs/colorValue",+ "description": "Thinking level border: minimal"+ },+ "thinkingLow": {+ "$ref": "#/$defs/colorValue",+ "description": "Thinking level border: low"+ },+ "thinkingMedium": {+ "$ref": "#/$defs/colorValue",+ "description": "Thinking level border: medium"+ },+ "thinkingHigh": {+ "$ref": "#/$defs/colorValue",+ "description": "Thinking level border: high"+ },+ "thinkingXhigh": {+ "$ref": "#/$defs/colorValue",+ "description": "Thinking level border: xhigh"+ },+ "thinkingMax": {+ "$ref": "#/$defs/colorValue",+ "description": "Thinking level border: max (falls back to thinkingXhigh when omitted)"+ },+ "bashMode": {+ "$ref": "#/$defs/colorValue",+ "description": "Editor border color in bash mode"+ }+ },+ "additionalProperties": false+ },+ "export": {+ "type": "object",+ "description": "Optional colors for HTML export (defaults derived from userMessageBg if not specified)",+ "properties": {+ "pageBg": {+ "$ref": "#/$defs/colorValue",+ "description": "Page background color"+ },+ "cardBg": {+ "$ref": "#/$defs/colorValue",+ "description": "Card/container background color"+ },+ "infoBg": {+ "$ref": "#/$defs/colorValue",+ "description": "Info sections background (system prompt, notices)"+ }+ },+ "additionalProperties": false+ }+ },+ "additionalProperties": false,+ "$defs": {+ "colorValue": {+ "oneOf": [+ {+ "type": "string",+ "description": "Hex color (#RRGGBB), variable reference, or empty string for terminal default"+ },+ {+ "type": "integer",+ "minimum": 0,+ "maximum": 255,+ "description": "256-color palette index (0-255)"+ }+ ]+ }+ }+}diff --git a/tools/pi/update.mjs b/tools/pi/update.mjsindex e51913bb43..8a03950e87 100644--- a/tools/pi/update.mjs+++ b/tools/pi/update.mjs@@ -42,6 +42,12 @@ const RELEASES_BY_TAG_URL = (tag) => `https://api.github.com/repos/earendil-workconst CACHE_FILE = path.join(__dirname, 'latest.json');const UPDATES_DIR = path.join(__dirname, 'updates');const BIN_DIR = path.join(PROJECT_ROOT, 'apps', 'pi-bin');+const THEME_SOURCE_DIR = path.join(__dirname, 'theme');+const REQUIRED_THEME_FILES = Object.freeze([+ 'theme/dark.json',+ 'theme/light.json',+ 'theme/theme-schema.json',+]);// 每个平台缓存目录记录“产出该缓存的归档 digest”(归一 64-hex)。上游若在同一 tag 下替换// 资产(digest 变、版本号不变),快速路径与 downloadAsset 跳过分支据此重新核验并重下 ——@@ -159,6 +165,35 @@ export function assetDigestMatchesUpstream(recordedDigest, asset) {return !!upstream && !!recorded && recorded === upstream;}+/**+ * Pi 0.84.x Windows archives may omit the themes that its startup path still+ * loads, so keep the small, version-compatible fallback assets in the repo.+ * Never overwrite a theme supplied by the upstream archive.+ */+export function ensurePiThemeAssets(destDir) {+ for (const relativePath of REQUIRED_THEME_FILES) {+ const destination = path.join(destDir, relativePath);+ if (fs.existsSync(destination)) continue;+ const source = path.join(THEME_SOURCE_DIR, path.basename(relativePath));+ if (!fs.existsSync(source)) {+ throw new Error(`Pi fallback theme asset missing: ${source}`);+ }+ fs.mkdirSync(path.dirname(destination), { recursive: true });+ fs.copyFileSync(source, destination);+ }+}++export function hasPiThemeAssets(destDir) {+ return REQUIRED_THEME_FILES.every((relativePath) => {+ const filePath = path.join(destDir, relativePath);+ try {+ return fs.statSync(filePath).isFile();+ } catch {+ return false;+ }+ });+}+/** 所有目标平台缓存记录的归档 digest 都与上游一致(同 tag 资产被替换时会不一致)。 */function targetsMatchUpstreamDigest(meta, version, targets) {return targets.every(({ key, asset: assetName }) => {@@ -199,7 +234,9 @@ function isUsableCache(filePath) {function targetsExist(version, targets) {return targets.every(({ key, binFile }) => {const dir = path.join(UPDATES_DIR, version, key);- return isUsableCache(path.join(dir, binFile)) && verifyDirDistManifest(dir);+ return isUsableCache(path.join(dir, binFile))+ && verifyDirDistManifest(dir)+ && hasPiThemeAssets(dir);});}@@ -270,6 +307,7 @@ async function downloadAsset(meta, version, platformKey, assetName, finalBinNameif (fs.existsSync(sha256Path)&& verifyDirDistManifest(destDir)+ && hasPiThemeAssets(destDir)&& assetDigestMatchesUpstream(readCachedAssetDigest(destDir), asset)) {const storedHash = fs.readFileSync(sha256Path, 'utf8').trim();@@ -317,6 +355,7 @@ async function downloadAsset(meta, version, platformKey, assetName, finalBinNameawait extractArchive(tmpArchive, destDir);flattenExtractedDir(destDir, finalBinName);+ ensurePiThemeAssets(destDir);fs.writeFileSync(finalBinPath + '.sha256.bin', sha256File(finalBinPath) + '\n');// 记录产出该缓存的归档 digest,供后续快速路径 / 跳过分支对上游同 tag 资产替换做核验。fs.writeFileSync(path.join(destDir, ASSET_DIGEST_FILE), verifiedDigest + '\n');