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
7 changes: 7 additions & 0 deletions src/agent/opencode-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ interface V2Headers {

export interface V2HttpRequestEvent {
sessionID?: unknown;
agent?: unknown;
model?: { providerID?: unknown; id?: unknown };
request?: { url?: unknown; headers?: V2Headers | null };
}
Expand Down Expand Up @@ -292,6 +293,12 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct
// instruction drift (AGENTS.md reconcile) must not fork the
// compression session.
headers.set("x-bili-plugin-instructions-mutable", "1");
// #1699: forward the host's per-request persona so the proxy can classify
// side requests by intent — opencode v2 title-gen carries no max_tokens, so
// the budget heuristic alone can never see it. Stamped for every non-empty
// id; the proxy acts only on known side-request agents (main ids are inert).
const agentId = typeof e.agent === "string" ? e.agent.trim() : "";
if (agentId.length > 0) headers.set("x-bili-plugin-agent", agentId);
const model = e.model;
if (model && typeof model.providerID === "string" && typeof model.id === "string") {
const key = `${model.providerID}/${model.id}`;
Expand Down
17 changes: 17 additions & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ export const PLUGIN_MODEL_HEADER = "x-bili-plugin-model";
* vestigial: hosts keep stamping it for protocol compatibility with older
* proxies, but current proxies key verbatim regardless. */
export const PLUGIN_INSTRUCTIONS_MUTABLE_HEADER = "x-bili-plugin-instructions-mutable";
/** #1699: the host's per-request persona/agent id (opencode v2 stamps its own
* taxonomy — "title", "build", "plan", ...). Carries INTENT the request body
* cannot express: opencode v2 title-gen requests carry NO max_tokens (options
* {} for kind==="title"), so the output-budget side-request heuristic (#388)
* can never see them — they were misclassified as main turns and got the full
* compress prompt + tool injected into the title model. The proxy acts only on
* known side-request agents (side-request.ts SIDE_REQUEST_AGENTS); main-persona
* ids are inert telemetry. */
export const PLUGIN_REQUEST_AGENT_HEADER = "x-bili-plugin-agent";

export const PLUGIN_PROTOCOL_VERSION = 1;

Expand Down Expand Up @@ -151,6 +160,14 @@ export function pluginReportedModel(headers: Record<string, string | string[] |
return raw !== undefined && /^\S{1,256}$/.test(raw) ? raw : undefined;
}

/** #1699: per-request persona id, honored ONLY from an announced plugin (same
* gate as window/model): a plain client must not be able to declare a side
* request by name to dodge compression. A real plugin stamps both headers. */
export function pluginRequestAgentHeader(headers: Record<string, string | string[] | undefined>): string | undefined {
if (pluginAgentHeader(headers) === undefined) return undefined;
return headerValue(headers, PLUGIN_REQUEST_AGENT_HEADER);
}

/** #956 hardening: per-request plugin window/max-output headers describe the
* model the plugin CONFIGURED — when the request body carries a different
* model (mid-switch race, or a provider-model composite like
Expand Down
10 changes: 7 additions & 3 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ import { affinityToken, claudeSubagentAgentId, claudeSubagentSplit, clientConver
import { prefixAffinity, type AnonymousAffinity } from "./prefix-affinity.js";
import { maybeAdoptForkBlocks, maybeAdoptResume } from "./fork-adoption.js";
import { flushPrefixAffinity, hydratePrefixAffinity, scheduleAffinityPersist } from "./affinity-persist.js";
import { consumePluginRegisterFor, flushConversations, handlePluginCompact, handlePluginManifest, handlePluginRegister, handlePluginRuntimeInfo, handlePluginStatus, handlePluginTool, isPluginFoldCallId, loadConversations, pipePluginChatWithStrip, pipePluginJson, pipePluginResponsesWithStrip, pluginAgentHeader, pluginConversationHeader, pluginHeadersMatchModel, pluginReportedContextWindow, pluginReportedMaxOutput, pluginRuntimeInfoFor, pluginRuntimeInfoForConversation, recordChainVerdict, recordPluginSession, rememberPluginMessages, resolveConversation, runtimeConversationId, takePendingPluginRegister } from "./plugin.js";
import { consumePluginRegisterFor, flushConversations, handlePluginCompact, handlePluginManifest, handlePluginRegister, handlePluginRuntimeInfo, handlePluginStatus, handlePluginTool, isPluginFoldCallId, loadConversations, pipePluginChatWithStrip, pipePluginJson, pipePluginResponsesWithStrip, pluginAgentHeader, pluginConversationHeader, pluginHeadersMatchModel, pluginReportedContextWindow, pluginReportedMaxOutput, pluginRequestAgentHeader, pluginRuntimeInfoFor, pluginRuntimeInfoForConversation, recordChainVerdict, recordPluginSession, rememberPluginMessages, resolveConversation, runtimeConversationId, takePendingPluginRegister } from "./plugin.js";
import { setupMitm, readMitmUpstream, getBlindTunnelStats, liveBlindTunnels } from "./mitm.js";
import { evaluateChain, extractChainCarriers, stampOutbound, stripEmbeddedChainCarriers } from "./chain-checkpoint.js";
import type { BiliMessage } from "acp-kernel/wire";
Expand Down Expand Up @@ -2347,7 +2347,11 @@ async function handle(
// the #460 render-tag strip pipes still run (response hygiene), while
// preflight / fake-completion retry / the loop / usage sniffing are all
// skipped. processedMessages stays empty so the loop can never engage.
if (!countTokens && !responsesCompact && protocol !== null && isSideRequest(parsed)) {
// #1699: opencode v2 title-gen requests carry no max_tokens, so the budget
// heuristic alone misses them. The host stamps its per-request persona id
// (x-bili-plugin-agent); a known side-request agent routes verbatim by intent.
const requestAgent = pluginRequestAgentHeader(req.headers);
if (!countTokens && !responsesCompact && protocol !== null && isSideRequest(parsed, requestAgent)) {
// #554: the passthrough below skips EVERY input-side guard by design
// (#388) — a full-history side request over the window is a
// guaranteed upstream 400 (and title-gen/probe clients re-issue it,
Expand Down Expand Up @@ -2378,7 +2382,7 @@ async function handle(
logRequestCost(log, session.id, inboundMsgs, inboundBytes, reqT0);
return;
}
log("info", `[${session.id}] side request (max_tokens<=${SIDE_REQUEST_MAX_TOKENS}) → passthrough + tag strip only, kernel state untouched`);
log("info", `[${session.id}] side request (${requestAgent !== undefined ? `agent=${requestAgent}` : `max_tokens<=${SIDE_REQUEST_MAX_TOKENS}`}) → passthrough + tag strip only, kernel state untouched`);
const sideBody = scrubAnthropicPck(protocol, bodyBuffer, log);
const sidePrepared: Prepared = {
body: sideBody,
Expand Down
11 changes: 10 additions & 1 deletion src/server/side-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,18 @@ import { type ResolvedImageBilling } from "../image-tokens.js";
// output budget from their raw (uncompressed) history shrink max_tokens to
// <=200 on long sessions; that must never demote the request to a side pass
// (title-gen requests never carry tools).
// #1699: explicit host intent outranks the budget heuristic. opencode v2 sends
// title-gen WITHOUT max_tokens (options {} for kind==="title"), so the budget
// path below can never see it; the host stamps its persona id
// (x-bili-plugin-agent) and a known side-request agent is a side req by
// definition regardless of budget.
export const SIDE_REQUEST_MAX_TOKENS = 200;
export function isSideRequest(parsed: unknown): boolean {
// Persona ids whose requests are side requests by intent (#1699). Main personas
// (build/plan/general/...) are deliberately absent — they are real turns.
export const SIDE_REQUEST_AGENTS: ReadonlySet<string> = new Set(["title"]);
export function isSideRequest(parsed: unknown, requestAgent?: string): boolean {
if (!parsed || typeof parsed !== "object") return false;
if (requestAgent !== undefined && SIDE_REQUEST_AGENTS.has(requestAgent)) return true;
const p = parsed as Record<string, unknown>;
if (Array.isArray(p.tools) && p.tools.length > 0) return false;
const field = outputBudgetField(parsed);
Expand Down
25 changes: 24 additions & 1 deletion tests/e2e/e2e-native-opencode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ type OracleEntry = {
toolName: string | null;
lastUser: string;
lastUserRef: string | null;
title?: boolean;
};

function readOracle(reqLog: string): OracleEntry[] {
Expand Down Expand Up @@ -622,13 +623,35 @@ if (checkOnly) {
const rows1 = readOracle(ctx.reqLog);
const conv = rows1.find((o) => o.conv)?.conv ?? null;
assert.ok(conv !== null && /^ses_/.test(conv), "run one must establish a session");
const fillerRow = rows1.find((o) => o.lastUser.includes("filler line 0"));
// #1699: skip the v2 title side-channel row — it re-sends the same
// filler text to the title model, and after intent-based routing it
// arrives VERBATIM (no ref tags, no tools); whichever of the two lands
// first in the reqLog is a race, so filter on the title marker.
const fillerRow = rows1.find((o) => o.lastUser.includes("filler line 0") && !o.title);
assert.ok(fillerRow, "filler prompt must reach the upstream (oracle)");
const targetRef = fillerRow.lastUserRef;
assert.ok(
targetRef !== null && /^m\d{5}$/.test(targetRef),
`filler message must carry its ACP ref tag, got ${targetRef} (row: ${JSON.stringify(fillerRow).slice(0, 200)})`,
);
// #1699 pin: any title rows present must be verbatim side-channel
// traffic — no kernel ref tags and no injected ACP tools — while the
// main turn above carries its ref. v1 title calls carry neither the
// v2 agent header nor max_tokens, so they were never side-classified
// (pre-existing v1 behavior, unchanged by this PR); gate on v2.
if ((info.major ?? 0) >= 2) {
for (const t of rows1.filter((o) => o.title)) {
assert.equal(
t.lastUserRef,
null,
`title side-channel must route verbatim (no ref tags), got ${t.lastUserRef}`,
);
assert.ok(
!t.tools.includes("compress"),
`title side-channel must not receive injected tools, got ${JSON.stringify(t.tools)}`,
);
}
}

await awaitProxyExit(ctx);

Expand Down
6 changes: 5 additions & 1 deletion tests/e2e/fake-upstream-chat.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ function answerFor(convKey, firstUserText, body) {
const isTitleCall =
messages.some((m) => m?.role === "system" && /title generator/i.test(stripAcps(flatContent(m.content)))) ||
users.some((u) => /^generate a title\b/i.test(stripAcps(flatContent(u.content)).trim()));
if (isTitleCall) return { content: "e2e-title", queueIdx: -1 };
if (isTitleCall) return { content: "e2e-title", queueIdx: -1, title: true };
const lastUserText = users.length > 0 ? flatContent(users[users.length - 1].content) : firstUserText;
let sourceText = lastUserText;
if (parseDirectives(lastUserText).length === 0 && users.length > 1) {
Expand Down Expand Up @@ -212,6 +212,10 @@ const server = http.createServer((req, res) => {
toolArgs: reply.toolArgs ?? null,
lastUser: firstUserText.slice(0, 120),
lastUserRef: lastUserRefMatch ? lastUserRefMatch[1] : null,
// #1699: title side-channel marker — after the fix these
// rows route VERBATIM (no ref tags, no injected tools),
// so suites must not mistake them for main turns.
title: reply.title === true,
}) + "\n");
} catch { /* noop */ }
if (parsed.stream) {
Expand Down
2 changes: 1 addition & 1 deletion tests/issue1086-chain-self-exemption.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -725,7 +725,7 @@ test("#1101 T9: BILI_CHAIN_CONTENT env parse — default OFF, 1 enables, env win
assert.equal(loadOptions({ BILI_CHAIN_CONTENT: "0" }).chainContentDetection, false, "env =0 wins over file true");
} finally {
if (prevFile === undefined) delete process.env.BILI_CONFIG_FILE; else process.env.BILI_CONFIG_FILE = prevFile;
rmSync(root, { recursive: true, force: true });
rmrf(root);
}
});

Expand Down
57 changes: 57 additions & 0 deletions tests/side-request-isolation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,24 @@ test("isSideRequest: tiny output budget across protocol field names", () => {
assert.equal(isSideRequest({ max_output_tokens: 16, tools: [{ type: "function", function: { name: "f" } }] }), false, "#546: responses wire, starved budget + tools → main");
});

test("isSideRequest: host-declared side-request agent outranks the token-budget heuristic (#1699)", () => {
// opencode v2 title-gen carries NO max_tokens (options {} for kind==="title"),
// so the budget path can never see it. Declaring the persona by intent fixes
// the misclassification without touching any request that omits max_tokens.
const noBudget = { messages: [{ role: "user", content: "Generate a short title." }] };
assert.equal(isSideRequest(noBudget, "title"), true, "#1699: no-budget title request is a side req by intent");
assert.equal(isSideRequest(noBudget), false, "same body WITHOUT the agent id stays non-side (no regression)");
// Intent outranks even the #546 tool-carrying main-turn guard (title-gen never
// carries tools; if it did, the host's explicit declaration wins).
assert.equal(isSideRequest({ max_tokens: 100, tools: [{ name: "compress" }] }, "title"), true, "#1699: intent beats the tools heuristic");
// A MAIN persona is never a side request — real turns keep compression.
assert.equal(isSideRequest({ max_tokens: 5000 }, "build"), false, "main persona with a normal budget is not a side req");
assert.equal(isSideRequest({}, "build"), false, "main persona without a budget is not a side req");
// An unknown persona id is inert — falls back to the token-budget heuristic.
assert.equal(isSideRequest({}, "unknown-persona"), false, "unknown persona does not grant side status");
assert.equal(isSideRequest({ max_tokens: 100 }, "unknown-persona"), true, "unknown persona still honors a tiny budget");
});

const noopLog = (): void => {};

function metaSession(id: string): { id: string; metadata: Record<string, unknown> } {
Expand Down Expand Up @@ -313,6 +331,45 @@ async function closeRig(rig: Rig): Promise<void> {
await once(rig.upstream, "close");
}

test("e2e: opencode v2 title-gen is classified by intent, not token budget (#1699)", async () => {
const rig = await startRig();
try {
const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`;
const baseHeaders: Record<string, string> = {
"content-type": "application/json",
"x-acp-session": SESSION,
"x-bili-plugin": "opencode",
"x-bili-plugin-conversation": SESSION,
};
// The exact opencode v2 title-gen shape that triggered the bug: one short
// instruction, NO max_tokens (options {} for kind==="title").
const titleBody = { model: MODEL, stream: true, messages: [{ role: "user", content: "Generate a short title for this conversation." }] };

// Repro (pre-fix behavior): WITHOUT x-bili-plugin-agent the budget heuristic
// sees no max_tokens → defaults to 8192 → NOT a side request → treated as a
// main turn, so the compress philosophy prompt + render tags get injected.
const rControl = await fetch(url, { method: "POST", headers: baseHeaders, body: JSON.stringify(titleBody) });
assert.equal(rControl.status, 200);
await rControl.text();
const controlFwd = rig.lastBody as { messages?: unknown } | null;
assert.ok(controlFwd, "control: upstream received the request");
assert.notDeepEqual(controlFwd?.messages, titleBody.messages, "control: without the agent header the title request is misclassified as a main turn and its messages are rewritten");
assert.ok(JSON.stringify(controlFwd ?? {}).length > JSON.stringify(titleBody).length + 1000, "control: the compress philosophy prompt inflated the forwarded payload (the reported ~11KiB injection)");

// Fix: WITH x-bili-plugin-agent=title the request is a side request by
// intent and is forwarded VERBATIM — its messages arrive byte-identical,
// nothing injected, kernel state untouched.
const rFix = await fetch(url, { method: "POST", headers: { ...baseHeaders, "x-bili-plugin-agent": "title" }, body: JSON.stringify(titleBody) });
assert.equal(rFix.status, 200);
await rFix.text();
const fixFwd = rig.lastBody as { messages?: unknown } | null;
assert.ok(fixFwd, "fix: upstream received the request");
assert.deepEqual(fixFwd?.messages, titleBody.messages, "fix: title-gen messages forwarded verbatim (no compress prompt/render tags injected)");
} finally {
await closeRig(rig);
}
});

test("e2e: side request response still gets render-tag stripping (#460 contract)", async () => {
const LT = "\x3c";
const GT = "\x3e";
Expand Down
Loading