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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions src/agent/native-intercept.ts
Original file line number Diff line number Diff line change
Expand Up @@ -918,11 +918,20 @@ function emptySlotOversizeRefusal(

/** #5405: same byte ceiling for an unattributed gate verdict. This is not a
* window-doom verdict (the 1M floor may still allow the body), so it needs
* its own marker and wording; retryable:true because attribution can return. */
function unattributedByteOversizeRefusal(url: string): Response {
* its own marker and wording; retryable:true because attribution can return.
* #7450: the ceiling is on TOTAL bytes but compression only acts on text —
* when the media split is known, name it in the message so the user can tell
* at a glance whether any folding could ever bring this body under the cap. */
function unattributedByteOversizeRefusal(url: string, detail: { bytes: number; cap: number; mediaBytes?: number }): Response {
const basis = `its body (${detail.bytes.toLocaleString("en-US")} B) is larger than the silent-direct byte ceiling (${detail.cap.toLocaleString("en-US")} B)`;
const remedy = detail.mediaBytes !== undefined && detail.mediaBytes > 0
? detail.mediaBytes >= detail.cap
? `Of those bytes, ${detail.mediaBytes.toLocaleString("en-US")} B is inline media (images/audio) that no compression can shrink — the media alone already exceeds the ceiling, so this conversation cannot fit under it as-is: start a fresh session or attach smaller images. Routing through a bili session will not remove the media.`
: `Of those bytes, ${detail.mediaBytes.toLocaleString("en-US")} B is inline media that compression cannot shrink; the rest is text a bili-managed session can fold. Route the conversation through a bili-managed session so the text can be compressed under the ceiling, or retry after the host re-establishes attribution.`
: "Route the conversation through a bili-managed session so it can be compressed, or retry after the host re-establishes attribution.";
const message =
"billion-context refused this request locally: it is not attributed to a bili-managed session and its body is larger than the silent-direct byte ceiling, so forwarding it would send a multi-megabyte prompt to the provider uncompressed (#5405). " +
"Route the conversation through a bili-managed session so it can be compressed, or retry after the host re-establishes attribution.";
"billion-context refused this request locally: it is not attributed to a bili-managed session and " + basis + ", so forwarding it would send a multi-megabyte prompt to the provider uncompressed (#5405). " +
remedy;
const headers = { "content-type": "application/json", "x-bili-gate": "oversize-refusal-unattributed-bytes" };
if (url.endsWith("/messages")) {
return new Response(JSON.stringify({ type: "error", error: { type: "invalid_request_error", message, retryable: true } }), { status: 422, headers });
Expand Down Expand Up @@ -1833,8 +1842,17 @@ export function installNativeFetchIntercept(initialState: NativeInterceptState):
: await outgoingBodyBytesCapped(defaultInput, init, cap);
if (silentBytes !== undefined && silentBytes > cap) {
state.onDispatch?.(dispatchUrl, "refused");
logHostEvent("error", "[native-client]", `bili-native: unattributed oversized model request refused locally with a 422 (${silentBytes.toLocaleString("en-US")} B > ${cap.toLocaleString("en-US")} B); would be sent uncompressed (#5405/#5408)`);
return unattributedByteOversizeRefusal(dispatchUrl);
// #7450: the ceiling is on TOTAL bytes but compression only
// acts on text — bill the incompressible media share (when
// the raw body is cheaply at hand) so the refusal and the
// log say whether any folding could ever bring this body
// under the cap.
const silentRaw = prep.outcome === "restored"
? prep.body
: measured?.raw ?? (typeof init?.body === "string" ? init.body : undefined);
const silentMediaBytes = silentRaw !== undefined ? mediaBytesOfWireBody(silentRaw) : undefined;
logHostEvent("error", "[native-client]", `bili-native: unattributed oversized model request refused locally with a 422 (${silentBytes.toLocaleString("en-US")} B > ${cap.toLocaleString("en-US")} B${silentMediaBytes !== undefined && silentMediaBytes > 0 ? `; ${silentMediaBytes.toLocaleString("en-US")} B inline media, incompressible` : ""}); would be sent uncompressed (#5405/#5408)`);
return unattributedByteOversizeRefusal(dispatchUrl, { bytes: silentBytes, cap, mediaBytes: silentMediaBytes });
}
}
// #4566: clean the stale hops only when a real send follows — the
Expand Down
61 changes: 61 additions & 0 deletions tests/native-intercept.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -791,6 +791,67 @@ test("install: an unattributed oversized request is refused before direct send (
assert.deepEqual(sink, [], "the oversized request must not reach the provider");
});

test("install: the unattributed byte-cap refusal names the incompressible media share (#7450)", async () => {
const savedEnv = process.env.BILI_SILENT_DIRECT_MAX_MB;
process.env.BILI_SILENT_DIRECT_MAX_MB = "1"; // 1 MiB cap keeps the test bodies small
const cap = 1024 * 1024;
try {
const state: NativeInterceptState = {
origin: "http://127.0.0.1:40914",
ready: Promise.resolve("http://127.0.0.1:40914"),
takeoverGate: () => false,
};
const { sink } = await withPatch(state, async (fetch) => {
// Dead-end case: the inline media alone exceeds the ceiling — no
// folding can ever bring the body under it.
const deadMedia = `data:image/png;base64,${"A".repeat(1_200_000)}`;
const deadBody = JSON.stringify({
model: "m",
messages: [{ role: "user", content: [
{ type: "text", text: "hi" },
{ type: "image_url", image_url: { url: deadMedia } },
] }],
});
assert.ok(Buffer.byteLength(deadBody) > cap, "dead-end body exceeds the 1 MiB cap");
const dead = await fetch("http://127.0.0.1:8199/v1/chat/completions", { method: "POST", body: deadBody });
assert.equal(dead.status, 422);
assert.equal(dead.headers.get("x-bili-gate"), "oversize-refusal-unattributed-bytes");
const dj = (await dead.json()) as { error: { message: string } };
assert.match(dj.error.message, new RegExp(deadMedia.length.toLocaleString("en-US") + " B is inline media"));
assert.match(dj.error.message, /media alone already exceeds the ceiling/);

// Foldable case: media under the ceiling, text pushes the total over —
// the remainder is text a bili session can fold.
const foldMedia = `data:image/png;base64,${"A".repeat(900_000)}`;
const foldBody = JSON.stringify({
model: "m",
messages: [{ role: "user", content: [
{ type: "text", text: "pad".repeat(60_000) },
{ type: "image_url", image_url: { url: foldMedia } },
] }],
});
assert.ok(Buffer.byteLength(foldBody) > cap, "foldable body exceeds the 1 MiB cap");
const fold = await fetch("http://127.0.0.1:8199/v1/chat/completions", { method: "POST", body: foldBody });
assert.equal(fold.status, 422);
const fj = (await fold.json()) as { error: { message: string } };
assert.match(fj.error.message, new RegExp(foldMedia.length.toLocaleString("en-US") + " B is inline media"));
assert.match(fj.error.message, /the rest is text a bili-managed session can fold/);

// Negative: a pure-text body over the cap keeps the legacy wording —
// no media claim, no byte-count basis change.
const text = await fetch("http://127.0.0.1:8199/v1/chat/completions", { method: "POST", body: "x".repeat(cap + 1) });
assert.equal(text.status, 422);
const tj = (await text.json()) as { error: { message: string } };
assert.doesNotMatch(tj.error.message, /inline media/);
assert.match(tj.error.message, /Route the conversation through a bili-managed session/);
});
assert.deepEqual(sink, [], "the oversized requests must not reach the provider");
} finally {
if (savedEnv === undefined) delete process.env.BILI_SILENT_DIRECT_MAX_MB;
else process.env.BILI_SILENT_DIRECT_MAX_MB = savedEnv;
}
});

test("install: a missing live-state slot refuses an oversized Request-object model body too (#5405/#5408)", async () => {
const saved = globalThis.fetch;
_resetForTest();
Expand Down
Loading