Skip to content

Commit 7ee56dd

Browse files
committed
fix(proxy): 指纹对齐 3.11.2 bundle——csn LLM 头序/UA SDK 后缀/双 auth 头/cache_control 先清后标/powered-by 并块
一次性切换(audit 批次 4,CL-25/26/27/28/29 + R2-22): - CL-27: identity.ts 拆分双构建器——buildLlmIdentityHeaders 镜像 bundle CLI csn+x4i(language/timezone 恒发回落 unknown、X-Release-Channel 紧随 X-Title、X-ZCode-Agent 居末、无 X-Device-Mid);buildIdentityHeaders(HRt 形态)保留供控制面(endpoint-routing/signing gate/claim/quota/async bridge);upstream.buildAuthHeaders 改用 LLM 构建器;docstring 改写为 csn/HRt 双函数分工 - CL-26: LLM 请求 UA 追加 ' ai-sdk/anthropic/3.0.81'(bundle Cm/k0o), 控制面 fetch 保持裸 ZCode UA(endpoint-routing/claim 测试钉住) - CL-25: coding-plan anthropic 请求在 x-api-key 之外追加同值 authorization: Bearer(bundle ebo);start-plan 仅 Authorization+jwt - CL-28: applyAnthropicCacheControl 两段式(zsi 清除非 system 消息既有 cache_control → Fsi 标最后一条),幂等——已是目标形状不再 re-serialize - CL-29: powered-by 行并入 Environment 块 text 末尾(T9o),不再独立第 4 块,cache_control 断点不变 - R2-22: identityCacheKey 抽至 identity.ts 共享(原 endpoint-routing 与 client-signing 两处逐字重复);normalizePrintableHeaderValue export 供 routes-quota 复用(替换其自实现 platform/arch 覆盖)
1 parent 6465ef7 commit 7ee56dd

12 files changed

Lines changed: 409 additions & 134 deletions

‎src/claim/client.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,13 +108,14 @@ describe("createClaimClient — getPreviews", () => {
108108

109109
describe("createClaimClient — identity header set", () => {
110110
it("preview and claim carry X-Device-Mid (server-required) and full identity minus X-ZCode-Agent", async () => {
111-
const seen: Array<{ path: string; deviceMid: string | null; agent: string | null; version: string | null }> = [];
111+
const seen: Array<{ path: string; deviceMid: string | null; agent: string | null; version: string | null; ua: string | null }> = [];
112112
const fetchImpl = makeMockFetch((req) => {
113113
seen.push({
114114
path: new URL(req.url).pathname,
115115
deviceMid: req.headers.get("x-device-mid"),
116116
agent: req.headers.get("x-zcode-agent"),
117117
version: req.headers.get("x-zcode-app-version"),
118+
ua: req.headers.get("user-agent"),
118119
});
119120
return Promise.resolve(jsonResp(PREVIEW_BODY));
120121
});
@@ -135,6 +136,9 @@ describe("createClaimClient — identity header set", () => {
135136
expect(r.deviceMid).toBe("d4ad5b5e-1234-4abc-9def-aabbccddeeff");
136137
expect(r.agent).toBeNull();
137138
expect(r.version).toBe("3.11.2");
139+
// CL-26: control-plane fetches keep the BARE ZCode UA — the
140+
// `ai-sdk/anthropic/...` suffix is LLM-path only.
141+
expect(r.ua).toBe("ZCode/3.11.2");
138142
}
139143
expect(seen[0].path).toBe("/api/v1/zcode-plan/billing/preview");
140144
expect(seen[1].path).toBe("/api/v1/zcode-plan/billing/claim");

‎src/proxy/body-transformer.test.ts‎

Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ describe("transformRequestBody — cache_control (Anthropic)", () => {
9898
expect(parsed.messages[0].content[0].cache_control).toEqual({ type: "ephemeral" });
9999
});
100100

101-
it("does NOT overwrite existing cache_control on last block", () => {
101+
it("clears a non-canonical existing cache_control and re-marks with the canonical ephemeral shape (zsi+Fsi)", () => {
102102
const existing = { type: "ephemeral", ttl: "1h" };
103103
const body = JSON.stringify({
104104
messages: [
@@ -107,7 +107,32 @@ describe("transformRequestBody — cache_control (Anthropic)", () => {
107107
});
108108
const out = transformRequestBody(body, { format: "anthropic" });
109109
const parsed = JSON.parse(out as string);
110-
expect(parsed.messages[0].content[0].cache_control).toEqual(existing);
110+
expect(parsed.messages[0].content[0].cache_control).toEqual({ type: "ephemeral" });
111+
});
112+
113+
it("strips client cache_control on earlier non-system messages, keeps only the last-message marker", () => {
114+
const body = JSON.stringify({
115+
messages: [
116+
{ role: "user", content: [{ type: "text", text: "early", cache_control: { type: "ephemeral" } }] },
117+
{ role: "assistant", content: [{ type: "text", text: "reply" }] },
118+
],
119+
});
120+
const out = transformRequestBody(body, { format: "anthropic" });
121+
const parsed = JSON.parse(out as string);
122+
expect(parsed.messages[0].content[0].cache_control).toBeUndefined();
123+
expect(parsed.messages[1].content[0].cache_control).toEqual({ type: "ephemeral" });
124+
});
125+
126+
it("is idempotent: an already-marked body is returned without modification", () => {
127+
const body = JSON.stringify({
128+
messages: [
129+
{ role: "user", content: [{ type: "text", text: "early" }] },
130+
{ role: "assistant", content: [{ type: "text", text: "reply", cache_control: { type: "ephemeral" } }] },
131+
],
132+
});
133+
const out = transformRequestBody(body, { format: "anthropic" });
134+
// Already our target shape → the original string comes back untouched
135+
expect(out).toBe(body);
111136
});
112137

113138
it("skips system messages — finds last non-system", () => {
@@ -164,7 +189,7 @@ describe("transformRequestBody — combined behavior", () => {
164189
});
165190

166191
describe("transformRequestBody — start-plan system (Anthropic)", () => {
167-
it("prepends current ZCode system messages as three cacheable blocks plus currentModel block", () => {
192+
it("prepends three official blocks with the currentModel line merged into the Environment block (T9o)", () => {
168193
const body = JSON.stringify({
169194
model: "glm-5.2",
170195
max_tokens: 1024,
@@ -174,7 +199,7 @@ describe("transformRequestBody — start-plan system (Anthropic)", () => {
174199
const out = transformRequestBody(body, { format: "anthropic", startPlan: true });
175200
const parsed = JSON.parse(out as string);
176201

177-
expect(parsed.system).toHaveLength(4);
202+
expect(parsed.system).toHaveLength(3);
178203
expect(parsed.system[0]).toEqual({
179204
type: "text",
180205
text: "You are ZCode, an interactive coding agent",
@@ -186,12 +211,10 @@ describe("transformRequestBody — start-plan system (Anthropic)", () => {
186211
expect(parsed.system[2].text).toContain("You have been invoked in the following environment:");
187212
expect(parsed.system[2].text).toContain("- Is a git repository: no");
188213
expect(parsed.system[2].text).not.toContain("- Is a git repository: unknown");
214+
// The powered-by line lives INSIDE the Environment text as its last line,
215+
// not as a separate 4th block (bundle 3.11.2 T9o shape).
216+
expect(parsed.system[2].text.endsWith("\n- You are powered by the model named glm-5.2.")).toBe(true);
189217
expect(parsed.system[2].cache_control).toEqual({ type: "ephemeral" });
190-
expect(parsed.system[3]).toEqual({
191-
type: "text",
192-
text: "- You are powered by the model named glm-5.2.",
193-
cache_control: { type: "ephemeral" },
194-
});
195218
});
196219

197220
it("omits the currentModel block when body.model is missing", () => {
@@ -241,13 +264,13 @@ describe("transformRequestBody — start-plan system (Anthropic)", () => {
241264
const out = transformRequestBody(body, { format: "anthropic", startPlan: true });
242265
const parsed = JSON.parse(out as string);
243266

244-
expect(parsed.system).toHaveLength(5);
245-
expect(parsed.system[4]).toEqual({ type: "text", text: "User rule" });
267+
expect(parsed.system).toHaveLength(4);
268+
expect(parsed.system[3]).toEqual({ type: "text", text: "User rule" });
246269
});
247270
});
248271

249272
describe("transformRequestBody — start-plan system (OpenAI)", () => {
250-
it("prepends current ZCode system messages (incl. currentModel) before OpenAI chat messages", () => {
273+
it("prepends current ZCode system messages (currentModel line inside the Environment message) before OpenAI chat messages", () => {
251274
const body = JSON.stringify({
252275
model: "glm-5.2",
253276
messages: [{ role: "user", content: "hi" }],
@@ -265,11 +288,8 @@ describe("transformRequestBody — start-plan system (OpenAI)", () => {
265288
expect(parsed.messages[2].role).toBe("system");
266289
expect(parsed.messages[2].content).toContain("You have been invoked in the following environment:");
267290
expect(parsed.messages[2].content).toContain("- Is a git repository: no");
268-
expect(parsed.messages[3]).toEqual({
269-
role: "system",
270-
content: "- You are powered by the model named glm-5.2.",
271-
});
272-
expect(parsed.messages[4]).toEqual({ role: "user", content: "hi" });
291+
expect(parsed.messages[2].content).toContain("- You are powered by the model named glm-5.2.");
292+
expect(parsed.messages[3]).toEqual({ role: "user", content: "hi" });
273293
});
274294

275295
it("omits the currentModel system message when body.model is missing (OpenAI)", () => {

‎src/proxy/body-transformer.ts‎

Lines changed: 48 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,12 @@
99
* (matches `@ai-sdk/openai-compatible` default in `_reverse/zcode.cjs`).
1010
* 2. start-plan → prepend ZCode gateway system blocks. OpenAI upstream gets
1111
* system messages; Anthropic-shaped input gets the Anthropic `system` field.
12-
* 3. Anthropic format → add `cache_control: { type: "ephemeral" }` to the
13-
* last non-system message (mirrors `HLr` ("finalizeLatestNonSystemCacheControl")
14-
* at offset ~636888 in the bundle). Anthropic's API silently ignores
15-
* `cache_control` below the per-model token floor, so unconditional add
16-
* is safe and matches ZCode's `applyCacheControl: true` default.
12+
* 3. Anthropic format → clear existing `cache_control` markers on all
13+
* non-system messages, then add `{ type: "ephemeral" }` to the last
14+
* content block of the last non-system message (mirrors the bundle's
15+
* `zsi`+`Fsi` pair). Anthropic's API silently ignores `cache_control`
16+
* below the per-model token floor, so unconditional marking is safe and
17+
* matches ZCode's `applyCacheControl: true` default.
1718
* 4. Anthropic format + `ctx.userId` set → inject `metadata: { user_id }`.
1819
* Mirrors `user_id: B.metadata.userId` at bundle offset ~4760586.
1920
*
@@ -85,14 +86,44 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {
8586
}
8687

8788
/**
88-
* Anthropic: add `cache_control: { type: "ephemeral" }` to the last content
89-
* block of the last non-system message. Mirrors ZCode's `HLr` algorithm.
90-
* Idempotent — skips if any block on that message already carries cache_control.
89+
* Anthropic: two-phase cache_control injection, mirroring the bundle's
90+
* `zsi` (clear) + `Fsi` (mark) pair:
91+
* (1) strip `cache_control` from every content block of every NON-system
92+
* message (string content carries no marker to clear);
93+
* (2) mark the last content block of the LAST non-system message (existing
94+
* location algorithm) with `{type: "ephemeral"}`; string content is
95+
* converted to a block array first (kept from the previous behavior).
96+
*
97+
* Without the clear phase, client-supplied `cache_control` on earlier messages
98+
* would pass through alongside our marker → multiple cache breakpoints and
99+
* more cache writes than the real client produces. The top-level `system`
100+
* field is untouched. The bundle's skipCacheWrite variant (marks the
101+
* second-to-last message instead) is NOT implemented — this proxy always
102+
* writes cache.
103+
*
104+
* Idempotent: when the body already has our target shape (no stray markers,
105+
* last block already `{type:"ephemeral"}`), nothing is reported as modified
106+
* so the caller skips re-serialization.
91107
*/
92108
function applyAnthropicCacheControl(body: Record<string, unknown>): boolean {
93109
const messages = body.messages;
94110
if (!Array.isArray(messages) || messages.length === 0) return false;
95111

112+
// Phase 1 (bundle `zsi`): clear stale markers on non-system messages.
113+
let cleaned = false;
114+
for (const msg of messages) {
115+
if (typeof msg !== "object" || msg === null) continue;
116+
if (msg.role === "system") continue;
117+
if (!Array.isArray(msg.content)) continue;
118+
for (const block of msg.content) {
119+
if (typeof block === "object" && block !== null && "cache_control" in block) {
120+
delete block.cache_control;
121+
cleaned = true;
122+
}
123+
}
124+
}
125+
126+
// Phase 2 (bundle `Fsi`): mark the last non-system message's last block.
96127
for (let i = messages.length - 1; i >= 0; i--) {
97128
const msg = messages[i];
98129
if (typeof msg !== "object" || msg === null) continue;
@@ -108,10 +139,13 @@ function applyAnthropicCacheControl(body: Record<string, unknown>): boolean {
108139
lastBlock.cache_control = { type: "ephemeral" };
109140
return true;
110141
}
142+
// Already marked — only report modified if the clear phase stripped
143+
// stray markers elsewhere (idempotency: avoid needless re-serialize).
144+
return cleaned;
111145
}
112-
return false;
146+
return cleaned;
113147
}
114-
return false;
148+
return cleaned;
115149
}
116150

117151
/**
@@ -133,9 +167,10 @@ function applyAnthropicUserId(body: Record<string, unknown>, userId: string): bo
133167
/**
134168
* start-plan: prepend ZCode gateway system blocks. The gateway rejects
135169
* requests without these identity blocks with 3012 "method not allowed".
136-
* Forwards `body.model` so `buildStartPlanSystem` can append the dynamic
137-
* "You are powered by the model named ${model}." block (matches bundle 3.3.6
138-
* `buildEnvInfoSection` behavior when `envInfo.currentModel` is set).
170+
* Forwards `body.model` so `buildStartPlanSystem` can merge the dynamic
171+
* "You are powered by the model named ${model}." line into the trailing
172+
* Environment block (matches bundle 3.11.2 `T9o`/buildEnvInfoSection — the
173+
* line lives INSIDE the Environment text, not as a separate block).
139174
*/
140175
function applyStartPlanSystem(body: Record<string, unknown>): boolean {
141176
const model = typeof body.model === "string" ? body.model : undefined;

‎src/proxy/client-signing.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
* Full protocol: `_reverse/NOTEPAD.md` "Client Request Signing V4".
1717
*/
1818
import type { UpstreamHeaderPair } from "./upstream.js";
19-
import { buildIdentityHeaders } from "./identity.js";
19+
import { buildIdentityHeaders, identityCacheKey } from "./identity.js";
2020
import type { ProxyIdentity } from "../config/types.js";
2121

2222
const DEFAULT_ORIGIN = "https://zcode.z.ai";
@@ -572,10 +572,6 @@ export async function sendWithClientSigning(
572572
let defaultSigner: ClientSigningManager | null = null;
573573
let defaultSignerKey = "";
574574

575-
function identityCacheKey(identity: ProxyIdentity): string {
576-
return JSON.stringify([identity.appVersion, identity.sourceTitle, identity.refererOrigin, identity.deviceMid ?? ""]);
577-
}
578-
579575
/**
580576
* Process-wide signing manager, shared across requests (gate + key caches).
581577
* Returns `null` when `clientSigning.enabled` is false. Recreated when the

‎src/proxy/endpoint-routing.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,26 @@ function okConfigFetch(...bodies: string[]): typeof fetch {
1717
}
1818

1919
describe("EndpointRoutingService", () => {
20+
it("config fetch carries the control-plane identity set with a BARE User-Agent (no SDK suffix)", async () => {
21+
// CL-26/CL-27: only the LLM request path carries the
22+
// `ai-sdk/anthropic/...` UA suffix and the csn header set — control-plane
23+
// fetches (endpoint routing) keep the HRt identity shape and bare UA.
24+
let seenUserAgent = "";
25+
const svc = new EndpointRoutingService({
26+
identity,
27+
fetchImpl: (async (_url: unknown, init?: RequestInit) => {
28+
const headers = new Headers(init?.headers);
29+
seenUserAgent = headers.get("User-Agent") ?? "";
30+
return new Response(JSON.stringify({
31+
code: 0,
32+
data: { proxyEndpoint: { mapping: [{ from: ZAI_ANTHROPIC, to: ZAI_ULTRA }] } },
33+
}), { status: 200, headers: { "content-type": "application/json" } });
34+
}) as unknown as typeof fetch,
35+
});
36+
await svc.resolve(ZAI_ANTHROPIC);
37+
expect(seenUserAgent).toBe("ZCode/3.8.1");
38+
});
39+
2040
it("rewrites a mapped URL and preserves the query string", async () => {
2141
const svc = new EndpointRoutingService({
2242
identity,

‎src/proxy/endpoint-routing.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
* previous snapshot (or none) and requests go to their original URL after a
1313
* cooldown. See `_reverse/NOTEPAD.md` "Server-side endpoint remapping".
1414
*/
15-
import { buildIdentityHeaders } from "./identity.js";
15+
import { buildIdentityHeaders, identityCacheKey } from "./identity.js";
1616
import type { ProxyIdentity } from "../config/types.js";
1717

1818
const DEFAULT_ORIGIN = "https://zcode.z.ai";
@@ -192,10 +192,6 @@ export class EndpointRoutingService {
192192
let defaultRouting: EndpointRoutingService | null = null;
193193
let defaultRoutingKey = "";
194194

195-
function identityCacheKey(identity: ProxyIdentity): string {
196-
return JSON.stringify([identity.appVersion, identity.sourceTitle, identity.refererOrigin, identity.deviceMid ?? ""]);
197-
}
198-
199195
/**
200196
* Process-wide routing service, shared across requests (snapshot cache).
201197
* Recreated when the relevant config values change (Android `setConfig`) —

0 commit comments

Comments
 (0)