From 6420b32741a2a47c453e435cd3b06efa7ab00cdc Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 29 Sep 2026 22:04:02 +0800 Subject: [PATCH 1/3] fix: classify opencode v2 title-gen by host-declared intent, not token budget (#1699) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit opencode v2 sends title-gen requests with NO max_tokens (options {} for kind==="title"), so bili's isTitleGen / side-request heuristic — which defaults a missing output budget to 8192 — misclassified them as main turns and injected the full ~11KiB compress philosophy prompt + ACP compress tool into the title model. Result: garbage session titles (English chat sentence / empty first line). Forward the host's per-request persona id on a new x-bili-plugin-agent header (stamped by the opencode v2 plugin from its own request scope) and treat a known side-request agent ("title") as a side request BY INTENT, routing it verbatim (no injection, kernel state untouched) regardless of output budget. Main personas (build/plan/general) are deliberately absent from the set, so real turns keep compression. The header reader is gated on plugin announcement so a plain client cannot declare a side request by name to dodge compression. Behavior change (intended): an opencode v2 title-gen request WITHOUT max_tokens now routes verbatim instead of being treated as a main turn. Previously it got the full compress philosophy prompt + tool injected; now it does not. This only affects requests that carry x-bili-plugin-agent: title; every other request is untouched. --- src/agent/opencode-v2.ts | 7 ++++ src/plugin.ts | 17 +++++++++ src/server.ts | 10 +++-- src/server/side-request.ts | 11 +++++- tests/side-request-isolation.test.ts | 57 ++++++++++++++++++++++++++++ 5 files changed, 98 insertions(+), 4 deletions(-) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index c04add105e..8d91dfab9b 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -69,6 +69,7 @@ interface V2Headers { export interface V2HttpRequestEvent { sessionID?: unknown; + agent?: unknown; model?: { providerID?: unknown; id?: unknown }; request?: { url?: unknown; headers?: V2Headers | null }; } @@ -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}`; diff --git a/src/plugin.ts b/src/plugin.ts index 649fda6aee..e781efe0a9 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -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; @@ -151,6 +160,14 @@ export function pluginReportedModel(headers: Record): 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 diff --git a/src/server.ts b/src/server.ts index f0576bfe8a..5e80d2d86e 100644 --- a/src/server.ts +++ b/src/server.ts @@ -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"; @@ -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, @@ -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, diff --git a/src/server/side-request.ts b/src/server/side-request.ts index 07e61f0e1b..acd2438bcb 100644 --- a/src/server/side-request.ts +++ b/src/server/side-request.ts @@ -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 = 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; if (Array.isArray(p.tools) && p.tools.length > 0) return false; const field = outputBudgetField(parsed); diff --git a/tests/side-request-isolation.test.ts b/tests/side-request-isolation.test.ts index 0069cdac57..c944db98a5 100644 --- a/tests/side-request-isolation.test.ts +++ b/tests/side-request-isolation.test.ts @@ -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 } { @@ -313,6 +331,45 @@ async function closeRig(rig: Rig): Promise { 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 = { + "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"; From fdc4d4067ecbe4804f1db3c043bd6585160d1808 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 29 Sep 2026 22:46:45 +0800 Subject: [PATCH 2/3] =?UTF-8?q?test:=20T9=20teardown=20uses=20rmrf=20helpe?= =?UTF-8?q?r=20=E2=80=94=20bare=20rmSync=20was=20never=20imported=20(#1655?= =?UTF-8?q?=20hardening=20dropped=20the=20import=20but=20missed=20this=20c?= =?UTF-8?q?all)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drive-by fix for a pre-existing master breakage found while reviewing PR #1703: master's CI is red because this finally block calls rmSync, which #1646/#1655 removed from the imports when converting teardowns to the retry-hardened rmrf helper (tests/tmp-rm.ts). Every other teardown in this file already uses rmrf; this one was missed. Without it, every PR merge-ref run fails here. --- tests/issue1086-chain-self-exemption.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/issue1086-chain-self-exemption.test.ts b/tests/issue1086-chain-self-exemption.test.ts index d0de78367e..dac34c8546 100644 --- a/tests/issue1086-chain-self-exemption.test.ts +++ b/tests/issue1086-chain-self-exemption.test.ts @@ -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); } }); From 29d302b87983ebfa5230d18df1a0f97942d5c0e7 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 29 Sep 2026 23:12:00 +0800 Subject: [PATCH 3/3] test(e2e): make opencode title side-channel race-safe + pin #1699 verbatim routing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI failed 'not ok 3' on the v2 lane: v2's title-gen request re-sends the first user message (the filler) to the title model concurrently with the main request, and after #1703 it routes VERBATIM — no ACP ref tags, no injected tools. Whichever row lands first in the reqLog is a race; when the title row won, find() matched it and the ref-tag assertion failed. - fake-upstream-chat.mjs: oracle rows now carry title:true (the detector already existed to answer title calls inertly). - test 3: skip title rows when locating the filler turn; add a v2-gated pin that title rows must arrive verbatim (lastUserRef null, no compress tool) — the #1699 regression pin. v1 title calls carry neither the v2 agent header nor max_tokens and were never side-classified; unchanged. Local: v2.0.3 lane 4/4, v1.14.47 lane 4/4, typecheck clean. --- tests/e2e/e2e-native-opencode.test.ts | 25 ++++++++++++++++++++++++- tests/e2e/fake-upstream-chat.mjs | 6 +++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/tests/e2e/e2e-native-opencode.test.ts b/tests/e2e/e2e-native-opencode.test.ts index 62ebea3344..9c51b7f231 100644 --- a/tests/e2e/e2e-native-opencode.test.ts +++ b/tests/e2e/e2e-native-opencode.test.ts @@ -119,6 +119,7 @@ type OracleEntry = { toolName: string | null; lastUser: string; lastUserRef: string | null; + title?: boolean; }; function readOracle(reqLog: string): OracleEntry[] { @@ -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); diff --git a/tests/e2e/fake-upstream-chat.mjs b/tests/e2e/fake-upstream-chat.mjs index 5a2fc017a5..6a0bbb479b 100644 --- a/tests/e2e/fake-upstream-chat.mjs +++ b/tests/e2e/fake-upstream-chat.mjs @@ -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) { @@ -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) {