From ed2d8da8e66d1b5bd16e5d90118ed87bcdf2fb18 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 21 Sep 2026 20:17:32 +0800 Subject: [PATCH 1/5] feat: output-side compression (verbosity steering + effort routing) Port headroom's two output-token levers to bili's forward boundary (#1093): - Verbosity steering: append a byte-stable conciseness directive (L0-L4, default L2) at the TAIL of the system prompt on all four wires (anthropic system, openai system/developer msg, responses instructions, google systemInstruction). Never prepends, never fabricates a system carrier when absent (skip-if-absent), idempotent so prefix cache stays hot. - Effort routing: structural turn classification of the final message list (no content pattern-matching); lowers an already-present effort field to its floor on mechanical continuations only. Never injects an effort field the client did not send, never toggles thinking.type. Default off; config in billion-context.json (global + per-provider route). Lives at the forward boundary after compat.roles so launcher/native-plugin/ /bili/ lanes inherit it; compress-retry re-sends share the same transform. Closes #1093 --- src/config.ts | 14 +- src/output-steering.ts | 461 ++++++++++++++++++++++++++++++++++ src/server.ts | 41 ++- tests/output-steering.test.ts | 252 +++++++++++++++++++ 4 files changed, 756 insertions(+), 12 deletions(-) create mode 100644 src/output-steering.ts create mode 100644 tests/output-steering.test.ts diff --git a/src/config.ts b/src/config.ts index 00799abb07..534d178e8e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -7,6 +7,7 @@ import { validateHttpProxy, type ProxyFallbackOptions } from "./upstream-proxy.j import { resolveOutputHeadroomCap } from "./util.js"; import { parseCompatRoles } from "./compat-roles.js"; +import { parseOutputSteering, DEFAULT_OUTPUT_STEERING, type OutputSteeringConfig } from "./output-steering.js"; import type { ImageBillingMode } from "./image-tokens.js"; import type { ReasoningGuardConfig } from "./reasoning-guard.js"; @@ -65,6 +66,8 @@ export type ProviderRoute = { * "auto" (default) classifies known first-party pixel hosts. Wins over * the global `imageBilling`; env BILI_IMAGE_BILLING wins over both. */ imageBilling?: ImageBillingMode; + /** Output-side compression override (#1093); wins over the global block. */ + outputSteering?: OutputSteeringConfig; }; export type ProviderRoutes = Record; // key = upstream URL prefix (the /bili/ string) @@ -428,6 +431,9 @@ export type ProxyOptions = { * forwarded body for upstreams without the developer role (#552). Empty = * byte-for-byte transparent. */ compat: { roles: Record }; + /** Output-side compression (#1093), resolved global default. A per-provider + * route `outputSteering` overlays it per request. Default OFF. */ + outputSteering: OutputSteeringConfig; /** Global-level image billing mode (#767); per-provider route entries * override it, env BILI_IMAGE_BILLING overrides both. undefined = auto. */ imageBilling?: ImageBillingMode; @@ -629,6 +635,7 @@ export function loadOptions(env: NodeJS.ProcessEnv = process.env): ProxyOptions routing: parsePromptCacheRouting(env.ACP_PROMPT_CACHE_ROUTING ?? fileConfig.promptCache?.routing), }, compat: { roles: parseCompatRoles(fileConfig.compat?.roles) ?? {} }, + outputSteering: parseOutputSteering(fileConfig.outputSteering) ?? DEFAULT_OUTPUT_STEERING, imageBilling: parseImageBilling(fileConfig.imageBilling), sessionHeader: env.ACP_SESSION_HEADER ?? fileConfig.sessionHeader ?? "x-acp-session", log: env.ACP_LOG !== "0" && fileConfig.log !== false, @@ -724,6 +731,9 @@ type FileConfig = { * brings a proxy up on. Default CLAUDE_NATIVE_DEFAULT_PORT; env * BILI_CLAUDE_NATIVE_PORT wins over both. */ claude?: { nativePort?: number }; + /** Output-side compression (#1093): verbosity steering + effort routing at + * the forward boundary. Default OFF; a per-provider route overlays it. */ + outputSteering?: { enabled?: boolean; verbosityLevel?: number; effortRouting?: boolean }; }; function nonEmpty(value: string | undefined): string | undefined { @@ -885,7 +895,7 @@ export function parseRouteEntry(v: unknown): ProviderRoute | undefined { // is the KEY in the providers map (identical to the /bili/ string), // so it is NOT repeated inside the value. if (v && typeof v === "object" && !Array.isArray(v)) { - const obj = v as { models?: Record; proxy?: string; compressProtocol?: string; compress?: CompressSettings; compat?: { roles?: unknown }; passthrough?: boolean; imageBilling?: unknown }; + const obj = v as { models?: Record; proxy?: string; compressProtocol?: string; compress?: CompressSettings; compat?: { roles?: unknown }; passthrough?: boolean; imageBilling?: unknown; outputSteering?: unknown }; const route: ProviderRoute = { models: obj.models }; if (typeof obj.proxy === "string") route.proxy = obj.proxy; if (obj.compressProtocol === "marker" || obj.compressProtocol === "tools") route.compressProtocol = obj.compressProtocol; @@ -895,6 +905,8 @@ export function parseRouteEntry(v: unknown): ProviderRoute | undefined { if (typeof obj.passthrough === "boolean") route.passthrough = obj.passthrough; const imageBilling = parseImageBilling(obj.imageBilling); if (imageBilling) route.imageBilling = imageBilling; + const outputSteering = parseOutputSteering(obj.outputSteering); + if (outputSteering) route.outputSteering = outputSteering; return route; } // A bare value (e.g. null) means "this upstream exists, no overrides". diff --git a/src/output-steering.ts b/src/output-steering.ts new file mode 100644 index 0000000000..da3f225228 --- /dev/null +++ b/src/output-steering.ts @@ -0,0 +1,461 @@ +import type { WireProtocol } from "./util.js"; + +/** + * Output-side compression (#1093): verbosity steering + effort routing. + * + * Ported from headroomlabs-ai/headroom (docs/proposals/output-token-reduction.md). + * Output tokens cost more than input and are billed the instant they stream out, + * so the only lever is at request time. Two levers, both applied at the proxy + * forward boundary AFTER every other body mutation, on the FINAL wire body: + * + * 1. Verbosity steering — append a deterministic conciseness directive at the + * TAIL of the system prompt (levels L0–L4, default L2; L0 = none). Never + * prepend: prepending shifts the client's own prompt bytes and busts the + * prefix cache. The directive is sentinel-wrapped and re-applied idempotently, + * so retries never accumulate it and a level change replaces in place. + * + * 2. Effort routing — classify the last user turn STRUCTURALLY (block + * composition only, no content pattern-matching); on a mechanical + * continuation (clean tool result, no error) LOWER an explicitly-present + * effort field toward its minimum. Clamp-only: NEVER inject a field the + * client didn't send (models without effort support 400 on it), and NEVER + * toggle `thinking.type` (disabling thinking over a history that carries + * thinking blocks 400s and busts the cache tier). + * + * Default OFF. Config: billion-context.json `outputSteering` block (global, with + * optional per-provider route overlay). Hard acceptance: no prefix-cache hit-rate + * regression (compare `[acp-usage]` cache hit %). + */ + +/** Sentinel wrapping the steering directive. Bili-owned (distinct from + * headroom's) so a body that passed through both proxies never collides. */ +const SENTINEL = ""; +const SUFFIX = ""; + +/** Conciseness directives L1–L4. BYTE-STABLE across releases: editing one is a + * prefix-cache bust for every session pinned at that level. Level 0 = none. */ +const VERBOSITY_LEVELS: Record = { + 1: "Skip preamble and postamble. Do not announce what you are about to do or recap what you just did; start with the substance.", + 2: "Skip preamble and postamble; start with the substance. Never restate code, file contents, diffs, or tool output that already appear in this conversation — reference them by path and line instead. After a tool call succeeds, continue without narrating the result.", + 3: "Skip preamble and postamble. Never restate code, file contents, diffs, or tool output already in this conversation — cite the exact file path and line or symbol instead, always; a reference that omits the location is not a reference. Give conclusions only; omit rationale unless the user asks why. Prefer the smallest edit over rewriting whole files. Keep prose to the minimum needed to be unambiguous. Never drop anything the turn or task needs to be correct, including negations (not, never, no, only, except) — shorten how you say it, not what you say. Use full prose for destructive or irreversible actions, security warnings, and any multi-step sequence where brevity would create ambiguity.", + 4: "Minimum tokens. Fragments fine. No preamble, no postamble, no restating context, no rationale. Answer, smallest-possible edits, nothing else. Never drop anything the turn or task needs to be correct, including negations (not, never, no, only, except). Use full prose for destructive or irreversible actions, security warnings, and any multi-step sequence where brevity would create ambiguity.", +}; + +export function steeringText(level: number): string | null { + const text = VERBOSITY_LEVELS[level]; + if (!text) return null; + return `${SENTINEL}\n${text}\n${SUFFIX}`; +} + +/** Idempotently place `block` in `existing`: replace the existing sentinel block + * in place (preserving surrounding text) if one is present, else append at the + * tail. Returns [updated, changed]. The slice skips PAST the old SUFFIX so a + * re-apply neither duplicates the closing tag nor grows the block. */ +function replaceOrAppend(existing: string, block: string): [string, boolean] { + const start = existing.indexOf(SENTINEL); + if (start >= 0) { + const found = existing.indexOf(SUFFIX, start); + const end = found < 0 ? existing.length : found + SUFFIX.length; + const prefix = existing.slice(0, start).replace(/\s+$/, ""); + const suffix = existing.slice(end).replace(/^\n+/, ""); + const parts = [prefix, block, suffix].filter((p) => p.length > 0); + const updated = parts.join("\n\n"); + return [updated, updated !== existing]; + } + const trimmed = existing.trim(); + const updated = trimmed.length > 0 ? `${existing.replace(/\s+$/, "")}\n\n${block}` : block; + return [updated, updated !== existing]; +} + +// ---- Config ---- + +export type OutputSteeringConfig = { + /** Master switch. Default OFF — both levers are inert until explicitly on. */ + enabled: boolean; + /** Verbosity level 0–4 (0 = no steering directive), default 2. */ + verbosityLevel: number; + /** Effort routing sub-switch, default on whenever `enabled` is. */ + effortRouting: boolean; +}; + +export const DEFAULT_OUTPUT_STEERING: OutputSteeringConfig = { + enabled: false, + verbosityLevel: 2, + effortRouting: true, +}; + +function clampVerbosityLevel(v: unknown): number { + if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4) return v; + return 2; +} + +/** Validate an `outputSteering`-shaped value. Malformed fields fall back to + * defaults rather than breaking the proxy; returns undefined when the value is + * not an object (caller substitutes DEFAULT_OUTPUT_STEERING). */ +export function parseOutputSteering(v: unknown): OutputSteeringConfig | undefined { + if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; + const obj = v as Record; + return { + enabled: obj.enabled === true, + verbosityLevel: clampVerbosityLevel(obj.verbosityLevel), + effortRouting: obj.effortRouting !== false, + }; +} + +// ---- Turn classification (pure structural, no content pattern-matching) ---- + +export type TurnKind = + | "new_user_ask" + | "mechanical_continuation" + | "error_continuation" + | "unknown"; + +function asRecord(v: unknown): Record | null { + return v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : null; +} + +/** Anthropic-style: a user turn's `content` is an array of typed blocks; tool + * results arrive as `tool_result` blocks inside the user message. */ +function classifyAnthropicTurn(messages: unknown): TurnKind { + if (!Array.isArray(messages) || messages.length === 0) return "unknown"; + const last = asRecord(messages[messages.length - 1]); + if (!last || last.role !== "user") return "unknown"; + const content = last.content; + if (typeof content === "string") return content.trim() ? "new_user_ask" : "unknown"; + if (!Array.isArray(content) || content.length === 0) return "unknown"; + let sawToolResult = false; + let sawError = false; + for (const raw of content) { + const b = asRecord(raw); + if (!b) return "unknown"; + const t = b.type; + if (t === "tool_result") { + sawToolResult = true; + if (b.is_error === true) sawError = true; + } else if (t === "text" || t === "image" || t === "document") { + return "new_user_ask"; + } + } + if (sawError) return "error_continuation"; + if (sawToolResult) return "mechanical_continuation"; + return "unknown"; +} + +/** OpenAI chat: tool results are separate `role:"tool"` messages (no structural + * error flag), so any trailing tool message is a mechanical continuation. */ +function classifyOpenAiChatTurn(messages: unknown): TurnKind { + if (!Array.isArray(messages) || messages.length === 0) return "unknown"; + const last = asRecord(messages[messages.length - 1]); + if (!last) return "unknown"; + if (last.role === "tool") return "mechanical_continuation"; + if (last.role === "user") { + const c = last.content; + if (typeof c === "string") return c.trim() ? "new_user_ask" : "unknown"; + if (Array.isArray(c)) { + for (const raw of c) { + const b = asRecord(raw); + if (b && b.type === "text" && typeof b.text === "string" && b.text.trim()) return "new_user_ask"; + } + return "unknown"; + } + return "unknown"; + } + return "unknown"; +} + +const RESPONSES_OUTPUT_TYPES = new Set([ + "custom_tool_call_output", + "function_call_output", + "local_shell_call_output", + "apply_patch_call_output", +]); + +function responsesUserSignal(item: Record): boolean { + if (item.role === "user") { + const c = item.content ?? item.input; + if (typeof c === "string") return c.trim().length > 0; + if (Array.isArray(c)) { + for (const raw of c) { + const b = asRecord(raw); + if (!b) continue; + if (b.type === "input_file" || b.type === "input_image") return true; + if (b.type === "input_text" && typeof b.text === "string" && b.text.trim()) return true; + } + } + return false; + } + if (item.type === "input_text") return typeof item.text === "string" && item.text.trim().length > 0; + if (item.type === "input_image") return true; + return false; +} + +/** Responses API: the whole `input` is a flat list of items. Mechanical means + * it carries tool-output items, no fresh user signal, and nothing unrecognized. */ +function classifyResponsesTurn(input: unknown): TurnKind { + if (typeof input === "string") return input.trim() ? "new_user_ask" : "unknown"; + if (!Array.isArray(input) || input.length === 0) return "unknown"; + let sawToolOutput = false; + let sawUnknown = false; + for (const raw of input) { + const item = asRecord(raw); + if (!item) { + sawUnknown = true; + continue; + } + const it = item.type; + if (typeof it === "string" && RESPONSES_OUTPUT_TYPES.has(it)) sawToolOutput = true; + else if (responsesUserSignal(item)) return "new_user_ask"; + else if (it === "message" || it === "function_call" || it === "reasoning") continue; + else sawUnknown = true; + } + if (sawToolOutput && !sawUnknown) return "mechanical_continuation"; + return "unknown"; +} + +/** Google native: the conversation is `contents`; a mechanical continuation is a + * final user turn whose parts are all `functionResponse` (no text/image). */ +function classifyGoogleTurn(contents: unknown): TurnKind { + if (!Array.isArray(contents) || contents.length === 0) return "unknown"; + const last = asRecord(contents[contents.length - 1]); + if (!last || last.role !== "user") return "unknown"; + const parts = last.parts; + if (!Array.isArray(parts) || parts.length === 0) return "unknown"; + let sawFunctionResponse = false; + for (const raw of parts) { + const p = asRecord(raw); + if (!p) return "unknown"; + if (p.functionResponse) { + sawFunctionResponse = true; + continue; + } + if (typeof p.text === "string" && p.text.trim()) return "new_user_ask"; + if (p.inlineData || p.fileData || p.videoMetadata) return "new_user_ask"; + } + if (sawFunctionResponse) return "mechanical_continuation"; + return "unknown"; +} + +function classifyTurn(protocol: WireProtocol, obj: Record): TurnKind { + switch (protocol) { + case "anthropic": return classifyAnthropicTurn(obj.messages); + case "openai": return classifyOpenAiChatTurn(obj.messages); + case "responses": return classifyResponsesTurn(obj.input); + case "google": return classifyGoogleTurn(obj.contents); + } +} + +// ---- Verbosity steering (append to the tail of the system prompt) ---- + +function steerSystemPrompt(obj: Record, protocol: WireProtocol, level: number): boolean { + const block = steeringText(level); + if (!block) return false; + switch (protocol) { + case "anthropic": return steerAnthropicSystem(obj, block); + case "openai": return steerOpenAiSystem(obj, block); + case "responses": return steerResponsesInstructions(obj, block); + case "google": return steerGoogleSystem(obj, block); + } +} + +function steerAnthropicSystem(obj: Record, block: string): boolean { + const sys = obj.system; + if (sys === undefined) return false; // skip-if-absent: never fabricate a system prompt + if (typeof sys === "string") { + const [updated, changed] = replaceOrAppend(sys, block); + if (changed) obj.system = updated; + return changed; + } + if (Array.isArray(sys)) { + for (const raw of sys) { + const b = asRecord(raw); + if (!b) continue; + const t = typeof b.text === "string" ? b.text : ""; + if (t.startsWith(SENTINEL)) { + if (t === block) return false; + b.text = block; + return true; + } + } + (sys as unknown[]).push({ type: "text", text: block }); + return true; + } + return false; +} + +function steerOpenAiSystem(obj: Record, block: string): boolean { + const msgs = obj.messages; + if (!Array.isArray(msgs)) return false; + const arr = msgs as Record[]; + let target: Record | null = null; + for (let i = arr.length - 1; i >= 0; i--) { + const m = arr[i]; + if (m && typeof m === "object" && (m.role === "system" || m.role === "developer")) { + target = m; + break; + } + } + if (!target) return false; // skip-if-absent + const content = target.content; + if (content === null || content === undefined) { + target.content = block; + return true; + } + if (typeof content === "string") { + const [updated, changed] = replaceOrAppend(content, block); + if (changed) target.content = updated; + return changed; + } + if (Array.isArray(content)) { + for (const raw of content) { + const b = asRecord(raw); + if (!b) continue; + if (b.type === "text" && typeof b.text === "string" && b.text.startsWith(SENTINEL)) { + if (b.text === block) return false; + b.text = block; + return true; + } + } + (content as unknown[]).push({ type: "text", text: block }); + return true; + } + return false; +} + +function steerResponsesInstructions(obj: Record, block: string): boolean { + const ins = obj.instructions; + if (ins === undefined) return false; // skip-if-absent + if (typeof ins !== "string") return false; + const [updated, changed] = replaceOrAppend(ins, block); + if (changed) obj.instructions = updated; + return changed; +} + +function steerGoogleSystem(obj: Record, block: string): boolean { + const si = asRecord(obj.systemInstruction); + if (!si) return false; // skip-if-absent + const parts = si.parts; + if (!Array.isArray(parts)) return false; + for (const raw of parts) { + const p = asRecord(raw); + if (!p) continue; + const t = typeof p.text === "string" ? p.text : ""; + if (t.startsWith(SENTINEL)) { + if (t === block) return false; + p.text = block; + return true; + } + } + (parts as unknown[]).push({ text: block }); + return true; +} + +// ---- Effort routing (clamp-only; never inject, never toggle thinking.type) ---- + +/** Documented API floor for Anthropic extended-thinking budget_tokens. */ +const ANTHROPIC_MIN_THINKING_BUDGET = 1024; +/** Assumed Gemini thinkingBudget floor; verify per-model before relying on it. */ +const GOOGLE_MIN_THINKING_BUDGET = 128; + +function lowerEffort(obj: Record, protocol: WireProtocol): boolean { + switch (protocol) { + case "openai": { + const e = obj.reasoning_effort; + if (typeof e === "string" && e !== "low") { + obj.reasoning_effort = "low"; + return true; + } + return false; + } + case "responses": { + const r = asRecord(obj.reasoning); + if (!r) return false; + const e = r.effort; + if (typeof e === "string" && e !== "low") { + r.effort = "low"; + return true; + } + return false; + } + case "anthropic": { + let changed = false; + const oc = asRecord(obj.output_config); + if (oc) { + const e = oc.effort; + if (typeof e === "string" && e !== "low") { + oc.effort = "low"; + changed = true; + } + } + const th = asRecord(obj.thinking); + if (th && typeof th.budget_tokens === "number" && th.budget_tokens > ANTHROPIC_MIN_THINKING_BUDGET) { + th.budget_tokens = ANTHROPIC_MIN_THINKING_BUDGET; + changed = true; + } + return changed; + } + case "google": { + const gc = asRecord(obj.generationConfig); + const tc = gc ? asRecord(gc.thinkingConfig) : null; + // -1 (dynamic) and values at/below the floor are left untouched. + if (tc && typeof tc.thinkingBudget === "number" && tc.thinkingBudget > GOOGLE_MIN_THINKING_BUDGET) { + tc.thinkingBudget = GOOGLE_MIN_THINKING_BUDGET; + return true; + } + return false; + } + } +} + +// ---- Entry points ---- + +/** Fallback wire detection when the caller has no resolved protocol (e.g. a + * passthrough forward where `prepared` is null): infer from the body shape. */ +function detectProtocolFromBody(obj: Record): WireProtocol | null { + if (Array.isArray(obj.input)) return "responses"; + if (Array.isArray(obj.contents)) return "google"; + if (Array.isArray(obj.messages)) { + // anthropic carries a top-level `system`; openai chat keeps it in messages + return obj.system !== undefined ? "anthropic" : "openai"; + } + return null; +} + +export interface SteeringResult { + body: string; + changed: boolean; + labels: string[]; +} + +/** Apply both levers to a serialized wire body. Returns the original string + * unchanged (no re-stringify) when nothing was mutated, so the default path + * stays byte-identical. Idempotent — safe to re-run on retry re-sends. */ +export function applyOutputSteering(body: string, protocol: WireProtocol | null, cfg: OutputSteeringConfig): SteeringResult { + if (!cfg.enabled) return { body, changed: false, labels: [] }; + let obj: Record; + try { + obj = JSON.parse(body) as Record; + } catch { + return { body, changed: false, labels: [] }; + } + const proto = protocol ?? detectProtocolFromBody(obj); + if (!proto) return { body, changed: false, labels: [] }; + const labels = applyOutputSteeringJson(obj, proto, cfg); + if (labels.length === 0) return { body, changed: false, labels: [] }; + return { body: JSON.stringify(obj), changed: true, labels }; +} + +/** Object-level variant shared by the forward boundary and the compress-retry + * re-send paths. Mutates `parsed` in place; returns the applied labels. */ +export function applyOutputSteeringJson(parsed: Record, protocol: WireProtocol | null, cfg: OutputSteeringConfig): string[] { + if (!cfg.enabled) return []; + const proto = protocol ?? detectProtocolFromBody(parsed); + if (!proto) return []; + const labels: string[] = []; + if (cfg.verbosityLevel > 0 && steerSystemPrompt(parsed, proto, cfg.verbosityLevel)) { + labels.push(`steering:L${cfg.verbosityLevel}`); + } + if (cfg.effortRouting && classifyTurn(proto, parsed) === "mechanical_continuation" && lowerEffort(parsed, proto)) { + labels.push("effort:low"); + } + return labels; +} diff --git a/src/server.ts b/src/server.ts index 5e9153cd4a..619adbeb16 100644 --- a/src/server.ts +++ b/src/server.ts @@ -107,6 +107,7 @@ import { dumpRejectedBody } from "./error-dump.js"; import { decodeRequestBody, DecompressedTooLargeError } from "./content-encoding.js"; import { applyCompatRoles, applyCompatRolesJson, detectRoleRejection, detectSystemPlacementError, resolveCompatRoles, type CompatRoles } from "./compat-roles.js"; +import { applyOutputSteering, applyOutputSteeringJson, DEFAULT_OUTPUT_STEERING } from "./output-steering.js"; import { bodyDumpEnabled, isModelDiscoveryPath, logDumpFailure, logUnrecognizedPath } from "./server/observability.js"; import { BILI_HOP_HEADER, anthropicBetaContextWindow, LAUNCHER_MODEL_WINDOWS, LAUNCHER_MODEL_MAX_OUTPUTS, launcherContextWindow, launcherMaxOutput, parseLauncherModelWindows, windowSourceLogged } from "./server/context-window.js"; import { buildForwardHeaders, connectionNamedHeaders, NO_IDENTITY_MESSAGE, RESPONSE_ONLY_STRIP_HEADERS, safeSessionId, UPSTREAM_HOP_HEADERS } from "./server/headers.js"; @@ -3948,6 +3949,12 @@ async function forward( let compatRoles: CompatRoles | null = null; let compatProtocol: "openai" | "responses" | null = null; const { upstreamUrl, headers, proxyUrl } = buildForwardTarget(req, opts, route, affinity, prepared !== null ? instanceId : undefined); + const wireProtocol = prepared?.protocol ?? route?.explicitProtocol ?? inferWireProtocol(req.url ?? ""); + // #1093: resolve output-side compression once here so the initial forward + // and every compress-retry re-send apply the SAME steering/effort config; + // a per-provider route entry wins over the global default. + const steerCfg = findRoute(opts.routes, upstreamUrl)?.outputSteering ?? opts.outputSteering ?? DEFAULT_OUTPUT_STEERING; + const steerEnabled = steerCfg.enabled; if (typeof body === "string") { // upstreamUrl (the real destination) — not route?.rewrittenUrl, which // is undefined for zero-config requests and would skip provider compat. @@ -3958,29 +3965,41 @@ async function forward( // config stays user-owned. const learned = (prepared?.session.metadata.learnedCompatRoles as CompatRoles | undefined) ?? {}; const roles = { ...configured, ...learned }; - const protocol = prepared?.protocol ?? route?.explicitProtocol ?? inferWireProtocol(req.url ?? ""); // compatProtocol is armed even with zero roles: the learn-on-failure // retry below needs it, and roles may be learned mid-request. - if (protocol === "openai" || protocol === "responses") { - compatProtocol = protocol; + if (wireProtocol === "openai" || wireProtocol === "responses") { + compatProtocol = wireProtocol; if (Object.keys(roles).length > 0) { compatRoles = roles; - const applied = applyCompatRoles(body, protocol, roles); + const applied = applyCompatRoles(body, wireProtocol, roles); if (applied.rewritten > 0) { wireBody = applied.body; log("info", `[${prepared?.session.id ?? "passthrough"}] [compat] rewrote ${applied.rewritten} message role(s) per compat.roles (${Object.entries(roles).map(([f, t]) => `${f}→${t}`).join(",")})`); } } } + // #1093: verbosity steering + effort routing run LAST, after compat.roles, + // so the turn classifier sees the final message list. Idempotent and + // byte-identical when disabled or when nothing matches. + if (steerEnabled && typeof wireBody === "string") { + const applied = applyOutputSteering(wireBody, wireProtocol, steerCfg); + if (applied.changed) { + wireBody = applied.body; + log("info", `[${prepared?.session.id ?? "passthrough"}] [output-steering] ${applied.labels.join(", ")}`); + } + } } - // #552: wire transform shared by ALL re-send paths (compress-retry loops - // below) so re-sent bodies carry the same rewrite as the initial forward — - // otherwise a developer-role 400 would hit mid-stream on the first retry. - // Reads compatRoles at CALL time: a role learned mid-request (retry below) - // applies to later re-sends within the same request. - const wireTransform = compatProtocol + // #552/#1093: wire transform shared by ALL re-send paths (compress-retry + // loops below) so re-sent bodies carry the same rewrite AND steering as the + // initial forward — otherwise a developer-role 400 would hit mid-stream on + // the first retry, or a retry would drop the directive/effort change. Both + // are read at CALL time (a role learned / config resolved mid-request applies + // to later re-sends within the same request). Steering is idempotent, so a + // re-send neither accumulates the directive nor re-lowers an already-low field. + const wireTransform = compatProtocol || steerEnabled ? (b: Record): Record => { - if (compatRoles) applyCompatRolesJson(b, compatProtocol, compatRoles); + if (compatProtocol && compatRoles) applyCompatRolesJson(b, compatProtocol, compatRoles); + if (steerEnabled) applyOutputSteeringJson(b, wireProtocol, steerCfg); return b; } : undefined; diff --git a/tests/output-steering.test.ts b/tests/output-steering.test.ts new file mode 100644 index 0000000000..0c412d534d --- /dev/null +++ b/tests/output-steering.test.ts @@ -0,0 +1,252 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + DEFAULT_OUTPUT_STEERING, + applyOutputSteering, + applyOutputSteeringJson, + parseOutputSteering, + steeringText, + type OutputSteeringConfig, +} from "../src/output-steering.ts"; + +const SENTINEL = ""; +const SUFFIX = ""; + +const ON: OutputSteeringConfig = { enabled: true, verbosityLevel: 2, effortRouting: true }; +const STEER_ONLY: OutputSteeringConfig = { enabled: true, verbosityLevel: 2, effortRouting: false }; +const EFFORT_ONLY: OutputSteeringConfig = { enabled: true, verbosityLevel: 0, effortRouting: true }; + +test("parseOutputSteering: non-object falls back to undefined (caller substitutes default)", () => { + assert.equal(parseOutputSteering(undefined), undefined); + assert.equal(parseOutputSteering(null), undefined); + assert.equal(parseOutputSteering("on"), undefined); + assert.equal(parseOutputSteering([]), undefined); +}); + +test("parseOutputSteering: defaults and clamping", () => { + assert.deepEqual(parseOutputSteering({}), { enabled: false, verbosityLevel: 2, effortRouting: true }); + assert.deepEqual(parseOutputSteering({ enabled: true }), { enabled: true, verbosityLevel: 2, effortRouting: true }); + assert.equal(parseOutputSteering({ enabled: true, verbosityLevel: 0 })?.verbosityLevel, 0); + assert.equal(parseOutputSteering({ enabled: true, verbosityLevel: 4 })?.verbosityLevel, 4); + assert.equal(parseOutputSteering({ enabled: true, verbosityLevel: 9 })?.verbosityLevel, 2); + assert.equal(parseOutputSteering({ enabled: true, verbosityLevel: -1 })?.verbosityLevel, 2); + assert.equal(parseOutputSteering({ enabled: true, verbosityLevel: 2.5 })?.verbosityLevel, 2); + assert.equal(parseOutputSteering({ enabled: "yes" })?.enabled, false); + assert.deepEqual(parseOutputSteering({ enabled: true, effortRouting: false }), { enabled: true, verbosityLevel: 2, effortRouting: false }); +}); + +test("DEFAULT_OUTPUT_STEERING is off by default", () => { + assert.equal(DEFAULT_OUTPUT_STEERING.enabled, false); +}); + +test("steeringText: L0 is none, L1-L4 are sentinel-wrapped and distinct", () => { + assert.equal(steeringText(0), null); + assert.equal(steeringText(5), null); + for (const lvl of [1, 2, 3, 4]) { + const t = steeringText(lvl)!; + assert.ok(t.startsWith(`${SENTINEL}\n`), `L${lvl} opens with sentinel`); + assert.ok(t.endsWith(SUFFIX), `L${lvl} closes with suffix`); + } + assert.notEqual(steeringText(2), steeringText(3)); +}); + +test("anthropic: appends to a string system prompt at the tail", () => { + const out = applyOutputSteering(JSON.stringify({ model: "m", system: "You are terse.", messages: [{ role: "user", content: "hi" }] }), "anthropic", STEER_ONLY); + assert.equal(out.changed, true); + assert.deepEqual(out.labels, ["steering:L2"]); + assert.ok((JSON.parse(out.body).system as string).endsWith(SUFFIX)); +}); + +test("anthropic: appends AFTER an array system, preserving cache_control breakpoints", () => { + const body = { model: "m", system: [{ type: "text", text: "a", cache_control: { type: "ephemeral" } }], messages: [{ role: "user", content: "hi" }] }; + const out = applyOutputSteering(JSON.stringify(body), "anthropic", STEER_ONLY); + const sys = JSON.parse(out.body).system as Array>; + assert.equal(sys.length, 2); + assert.deepEqual(sys[0].cache_control, { type: "ephemeral" }, "earlier breakpoint untouched"); + assert.ok(String(sys[1].text).startsWith(SENTINEL), "directive appended after the last block"); +}); + +test("openai: appends to the last system OR developer message content", () => { + for (const role of ["system", "developer"]) { + const out = applyOutputSteering(JSON.stringify({ model: "m", messages: [{ role, content: "sys" }, { role: "user", content: "hi" }] }), "openai", STEER_ONLY); + assert.equal(out.changed, true, `${role} targeted`); + assert.ok((JSON.parse(out.body).messages[0].content as string).endsWith(SUFFIX)); + } +}); + +test("responses: appends to the instructions string", () => { + const out = applyOutputSteering(JSON.stringify({ model: "m", instructions: "base", input: [{ type: "message", role: "user", content: "hi" }] }), "responses", STEER_ONLY); + assert.equal(out.changed, true); + assert.ok((JSON.parse(out.body).instructions as string).endsWith(SUFFIX)); +}); + +test("google: appends a part to systemInstruction.parts", () => { + const body = { model: "m", systemInstruction: { parts: [{ text: "base" }] }, contents: [{ role: "user", parts: [{ text: "hi" }] }] }; + const out = applyOutputSteering(JSON.stringify(body), "google", STEER_ONLY); + const parts = (JSON.parse(out.body).systemInstruction as { parts: Array<{ text: string }> }).parts; + assert.equal(parts.length, 2); + assert.ok(parts[1].text.startsWith(SENTINEL)); +}); + +test("skip-if-absent: no system carrier means no fabrication, byte-identical", () => { + const cases: Array<[string, string]> = [ + ["anthropic", JSON.stringify({ model: "m", messages: [{ role: "user", content: "hi" }] })], + ["openai", JSON.stringify({ model: "m", messages: [{ role: "user", content: "hi" }] })], + ["responses", JSON.stringify({ model: "m", input: [{ type: "message", role: "user", content: "hi" }] })], + ["google", JSON.stringify({ model: "m", contents: [{ role: "user", parts: [{ text: "hi" }] }] })], + ]; + for (const [proto, s] of cases) { + const out = applyOutputSteering(s, proto as "anthropic", STEER_ONLY); + assert.equal(out.changed, false, `${proto}: nothing to attach to`); + assert.equal(out.body, s, `${proto}: byte-identical`); + assert.deepEqual(out.labels, []); + } +}); + +test("idempotent: same-level re-apply is a byte-stable no-op", () => { + const base = JSON.stringify({ model: "m", instructions: "You are terse." }); + const first = applyOutputSteering(base, "responses", ON); + assert.equal(first.changed, true); + assert.deepEqual(first.labels, ["steering:L2"]); + + const second = applyOutputSteering(first.body, "responses", ON); + assert.equal(second.changed, false, "re-applying the same level must not mutate"); + assert.equal(second.body, first.body, "...and must be byte-identical"); + assert.deepEqual(second.labels, []); +}); + +test("idempotent: a level change REPLACES the block in place (no duplication)", () => { + const first = applyOutputSteering(JSON.stringify({ model: "m", instructions: "You are terse." }), "responses", ON); + const third = applyOutputSteering(first.body, "responses", { ...ON, verbosityLevel: 3 }); + assert.equal(third.changed, true); + const ins = JSON.parse(third.body).instructions as string; + assert.equal(ins.split(SENTINEL).length - 1, 1, "exactly one steering block after a level change"); + assert.notEqual(third.body, first.body); +}); + +test("anthropic: mechanical continuation lowers effort + clamps thinking budget", () => { + const body = { + model: "m", + system: "b", + messages: [{ role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "ok" }] }], + output_config: { effort: "xhigh" }, + thinking: { type: "enabled", budget_tokens: 16000 }, + }; + const out = applyOutputSteering(JSON.stringify(body), "anthropic", EFFORT_ONLY); + assert.equal(out.changed, true); + assert.deepEqual(out.labels, ["effort:low"]); + const p = JSON.parse(out.body); + assert.equal(p.output_config.effort, "low"); + assert.equal(p.thinking.budget_tokens, 1024, "budget clamped to API floor"); +}); + +test("anthropic: error continuation leaves effort untouched", () => { + const body = { + model: "m", + messages: [{ role: "user", content: [{ type: "tool_result", tool_use_id: "t1", is_error: true, content: "boom" }] }], + output_config: { effort: "xhigh" }, + }; + const out = applyOutputSteering(JSON.stringify(body), "anthropic", EFFORT_ONLY); + assert.equal(out.changed, false); + assert.deepEqual(out.labels, []); + assert.equal(JSON.parse(out.body).output_config.effort, "xhigh"); +}); + +test("anthropic: never injects effort fields the client did not send", () => { + const s = JSON.stringify({ model: "m", messages: [{ role: "user", content: [{ type: "tool_result", tool_use_id: "t", content: "x" }] }] }); + const out = applyOutputSteering(s, "anthropic", EFFORT_ONLY); + assert.equal(out.changed, false); + assert.equal(out.body, s); + assert.ok(!("output_config" in JSON.parse(out.body)), "no fabricated output_config"); + assert.ok(!("thinking" in JSON.parse(out.body)), "no fabricated thinking"); +}); + +test("openai: trailing tool message lowers reasoning_effort; a real user turn does not", () => { + const mech = { model: "m", messages: [{ role: "user", content: "hi" }, { role: "assistant", content: "", tool_calls: [{ id: "c", type: "function", function: { name: "f", arguments: "{}" } }] }, { role: "tool", tool_call_id: "c", content: "result" }], reasoning_effort: "high" }; + const outM = applyOutputSteering(JSON.stringify(mech), "openai", EFFORT_ONLY); + assert.deepEqual(outM.labels, ["effort:low"]); + assert.equal(JSON.parse(outM.body).reasoning_effort, "low"); + + const ask = { model: "m", messages: [{ role: "user", content: "hi" }, { role: "assistant", content: "" }, { role: "user", content: "next" }], reasoning_effort: "high" }; + const outA = applyOutputSteering(JSON.stringify(ask), "openai", EFFORT_ONLY); + assert.equal(outA.changed, false); + assert.equal(JSON.parse(outA.body).reasoning_effort, "high", "non-mechanical turn untouched"); + + const noField = { model: "m", messages: [{ role: "tool", tool_call_id: "c", content: "r" }] }; + assert.equal(applyOutputSteering(JSON.stringify(noField), "openai", EFFORT_ONLY).changed, false, "no injection when reasoning_effort absent"); +}); + +test("responses: tool-output-only input lowers reasoning.effort; a user signal does not", () => { + const mech = { model: "m", input: [{ type: "function_call_output", call_id: "c", output: "{}" }, { type: "message", role: "assistant", content: [{ type: "output_text", text: "done" }] }], reasoning: { effort: "high" } }; + const outM = applyOutputSteering(JSON.stringify(mech), "responses", EFFORT_ONLY); + assert.deepEqual(outM.labels, ["effort:low"]); + assert.equal((JSON.parse(outM.body).reasoning as { effort: string }).effort, "low"); + + const ask = { model: "m", input: [{ role: "user", content: [{ type: "input_text", text: "do X" }] }], reasoning: { effort: "high" } }; + const outA = applyOutputSteering(JSON.stringify(ask), "responses", EFFORT_ONLY); + assert.equal(outA.changed, false); + assert.equal((JSON.parse(outA.body).reasoning as { effort: string }).effort, "high"); +}); + +test("google: functionResponse-only turn clamps thinkingBudget; dynamic (-1) and text turns untouched", () => { + const mech = { model: "m", contents: [{ role: "user", parts: [{ functionResponse: { name: "f", response: {} } }] }], generationConfig: { thinkingConfig: { thinkingBudget: 8000 } } }; + const outM = applyOutputSteering(JSON.stringify(mech), "google", EFFORT_ONLY); + assert.deepEqual(outM.labels, ["effort:low"]); + assert.equal((JSON.parse(outM.body).generationConfig.thinkingConfig as { thinkingBudget: number }).thinkingBudget, 128); + + const dyn = { model: "m", contents: [{ role: "user", parts: [{ functionResponse: { name: "f", response: {} } }] }], generationConfig: { thinkingConfig: { thinkingBudget: -1 } } }; + assert.equal(applyOutputSteering(JSON.stringify(dyn), "google", EFFORT_ONLY).changed, false, "dynamic budget left alone"); + + const ask = { model: "m", contents: [{ role: "user", parts: [{ text: "hello" }] }], generationConfig: { thinkingConfig: { thinkingBudget: 8000 } } }; + assert.equal(applyOutputSteering(JSON.stringify(ask), "google", EFFORT_ONLY).changed, false, "a real user turn is not mechanical"); +}); + +test("both levers fire on a steerable mechanical turn, labels ordered steering-then-effort", () => { + const body = { + model: "m", + system: "b", + messages: [{ role: "user", content: [{ type: "tool_result", tool_use_id: "t", content: "x" }] }], + output_config: { effort: "high" }, + }; + const out = applyOutputSteering(JSON.stringify(body), "anthropic", ON); + assert.deepEqual(out.labels, ["steering:L2", "effort:low"]); + assert.equal(JSON.parse(out.body).output_config.effort, "low"); +}); + +test("default (disabled) is byte-transparent for every wire", () => { + const s = JSON.stringify({ model: "m", instructions: "x", input: [], reasoning: { effort: "high" } }); + const out = applyOutputSteering(s, "responses", DEFAULT_OUTPUT_STEERING); + assert.equal(out.body, s); + assert.equal(out.changed, false); + assert.deepEqual(out.labels, []); +}); + +test("null protocol: inferred from body shape", () => { + const responses = applyOutputSteering(JSON.stringify({ model: "m", instructions: "b", input: [{ type: "message", role: "user", content: "h" }] }), null, STEER_ONLY); + assert.equal(responses.changed, true, "input[] → responses"); + + const anthropic = applyOutputSteering(JSON.stringify({ model: "m", system: "b", messages: [{ role: "user", content: "h" }] }), null, STEER_ONLY); + assert.equal(anthropic.changed, true, "top-level system → anthropic"); + + const openai = applyOutputSteering(JSON.stringify({ model: "m", messages: [{ role: "system", content: "b" }, { role: "user", content: "h" }] }), null, STEER_ONLY); + assert.equal(openai.changed, true, "messages without top-level system → openai"); + + const google = applyOutputSteering(JSON.stringify({ model: "m", systemInstruction: { parts: [{ text: "b" }] }, contents: [{ role: "user", parts: [{ text: "h" }] }] }), null, STEER_ONLY); + assert.equal(google.changed, true, "contents[] → google"); + + const unknown = applyOutputSteering(JSON.stringify({ model: "m" }), null, STEER_ONLY); + assert.equal(unknown.changed, false, "unrecognizable shape → no-op"); +}); + +test("invalid JSON is returned verbatim", () => { + const out = applyOutputSteering("not json", "openai", ON); + assert.equal(out.body, "not json"); + assert.equal(out.changed, false); +}); + +test("applyOutputSteeringJson mutates in place and is idempotent", () => { + const obj = { model: "m", instructions: "base" } as Record; + assert.deepEqual(applyOutputSteeringJson(obj, "responses", STEER_ONLY), ["steering:L2"]); + assert.deepEqual(applyOutputSteeringJson(obj, "responses", STEER_ONLY), [], "second pass finds the block already present"); + assert.ok(String(obj.instructions).includes(SENTINEL)); +}); From e4dbfe459e0f0e9c6fe2726dc5b6c97f4fdedf9c Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 21 Sep 2026 20:44:34 +0800 Subject: [PATCH 2/5] fix: responses effort routing classified full-history turns as new asks (#1093) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round on PR #1096: the Responses turn classifier scanned the flat input list FORWARD for any user signal. Clients re-send full history every request (codex does), so the original ask was present on every turn and the classifier returned new_user_ask unconditionally — effort routing could only fire on delta-only inputs that never occur through bili. The other three wires classify the LAST message correctly, so this made effort routing dead on the flagship codex lane while appearing functional in tests (whose synthetic inputs carry no prior user message). - classifyResponsesTurn now walks BACKWARD from the tail: tool outputs after the last user signal = mechanical continuation; a user signal at the tail or with no outputs after it = new_user_ask. Assistant-side items between the last user signal and the trailing outputs no longer break the continuation (message/function_call/custom_tool_call/local_shell_call/ apply_patch_call/reasoning — previously custom/local/apply-patch calls marked the turn unknown even in the delta case). - Anthropic + Google classifiers: unrecognized block/part composition now returns unknown instead of being silently skipped (all four wires share one conservative stance: unrecognized structure => do not classify). - 6 regression tests incl. the realistic full-history repro; steering suite 23 -> 29, all green. - Docs: outputSteering entries in CONFIGURATION.md + CONFIGURATION.zh-CN.md (global + per-provider), CHANGELOG [Unreleased] entry. --- CHANGELOG.md | 5 +++ CONFIGURATION.md | 17 ++++++++ CONFIGURATION.zh-CN.md | 17 ++++++++ src/output-steering.ts | 48 +++++++++++++++------- tests/output-steering.test.ts | 76 +++++++++++++++++++++++++++++++++++ 5 files changed, 148 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dcc3bb6591..a07e51dce5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,11 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ### Features +- **Output-side compression: verbosity steering + effort routing (#1093)**: ports headroom's two output-token levers to bili's forward boundary. Output tokens cost ~5× input and are billed the instant they stream out, so the only lever is at request time. Both levers are **default off** (zero behavior change until enabled) and run LAST at the forward boundary — after every other body mutation, after `compat.roles` — so the turn classifier sees the final wire list; compress-retry re-sends share the same idempotent transform (`wireTransform`), and launcher / native-plugin / `/bili/` lanes inherit automatically. When disabled the path is byte-identical (no parse, no re-serialize). + - *Verbosity steering* appends a byte-stable conciseness directive (levels L0–L4, default L2) at the **tail** of the system prompt. Never prepends (that busts the prefix cache); **skip-if-absent** — it never fabricates a system carrier the client didn't send (a newly injected system can itself be rejected by placement-strict backends, #377 class); sentinel-wrapped and idempotent — re-applying the same level is a byte-stable no-op, a level change replaces the block in place, so retries never accumulate it. Covers all four wires: Anthropic `system` (string + block array, `cache_control` breakpoints preserved), OpenAI `system`/`developer` message, Responses `instructions`, Google `systemInstruction.parts`. + - *Effort routing* classifies the final turn **structurally** (block composition only, no content pattern-matching) and, on a mechanical continuation turn (clean tool result, no error), lowers an **already-present** effort field toward its floor: OpenAI `reasoning_effort`→`low`; Responses `reasoning.effort`→`low`; Anthropic `output_config.effort`→`low` + `thinking.budget_tokens`→1024 (documented API floor); Google `generationConfig.thinkingConfig.thinkingBudget`→128 (**assumed** floor, documented as such). Clamp-only safety rules: never injects an effort field the client didn't send (models without effort support 400 on it), never toggles `thinking.type` (disabling thinking over a history that carries thinking blocks 400s and busts the cache tier), dynamic budgets (`-1`) and non-mechanical turns untouched, unrecognized structural shapes not classified (conservative — request goes out unchanged). The Responses classifier walks the flat `input` list BACKWARD from the tail: clients re-send full history every request (codex does), so a forward scan would hit the original ask on every turn and could never classify a continuation; assistant-side items between the last user signal and the trailing tool outputs (`message`, `function_call`, `custom_tool_call`, `local_shell_call`, `apply_patch_call`, `reasoning`) do not break the continuation. + - Config: `billion-context.json` `outputSteering` block (global + per-provider route overlay, same shape as `compat`). 29 regression tests across all four wires (idempotency, skip-if-absent, clamp-only rules, full-history continuation classification). + - **Coexistence marker for standalone extensions (#820)**: the pi-native and opencode-native entries now set `BILLION_CONTEXT_NATIVE=` synchronously at module evaluation (gated on their own bootstrap gate, first writer wins — `markNativeHost()` in `src/agent/native-bootstrap.ts`), so the standalone `billion-context-pi` / `opencode-acp` extensions can stand down at action time when running alongside a native entry. Verified against both sibling repos that the pre-existing auto-disable does NOT cover native mode: they check `BILLION_CONTEXT_PROXY` only at extension-load time (native bootstrap writes it asynchronously, after the proxy is up) and detect `/bili/` in the configured baseUrl (native rewrites at the fetch layer, invisible to config); launcher mode and manual wiring keep working as before. Standalone-side adoption of the marker is tracked in each repo's issue tracker. - **opencode 2.x native mode: package-installed opencode gets plugin-mode compression with no launcher (#820, npm-package design #809)**: `bili plugin install opencode` now installs, alongside the MCP shell (kept, but optional — a missing live proxy origin skips it instead of failing the install), a self-spawning native plugin: a stable wrapper directory `/plugins/billion-context/index.js` re-exporting `dist/agent/opencode-native.js` (OpenCode 2.x rejects bare FILE paths in `plugin` — the directory's index.js is the entrypoint, #754 probe) plus `compaction.auto=false` (single compression owner; merge-preserving, restored from the `.bili-bak` backup on remove). At plugin load the same gate as pi-native applies (`BILI_NATIVE_OPENCODE=0` opt-out; skipped entirely under a `bili` launch) and the package's own proxy is bootstrapped through `ensureProxyRunning` (attach-or-spawn, ephemeral port, parent-pid watchdog, `deps.scriptPath`). OpenCode plugins have no fetch seam to patch, so egress interception uses the `http.request` hook, replacing the outgoing fetch Request REFERENCE with `new Request("/bili/", old)` carrying method/headers/body (WHATWG Request.url is read-only at runtime — verified live, #810). Header stamping, native tools and compaction-boundary reporting reuse the shared V2 setup factory (`src/agent/opencode-v2.ts`, extracted from opencode.ts so launcher mode and native mode share ONE protocol implementation). Because an http.request hook cannot observe send failures (the host swallows them), every request liveness-probes `/__bili/health` of the current origin before routing — one respawn if the proxy died mid-session, direct send + one-time warning when no origin can be made healthy (auto-recovering: each request re-verifies, unlike pi's lifetime latch). Also fixes #819: `ensureProxyRunning` resolves the Node executable for spawning via `resolveNodeRuntime()` (live Node wins → `BILLION_CONTEXT_NODE` override → PATH search) instead of blind `process.execPath`, which inside a host binary (opencode/pi native) is the HOST executable — the spawned proxy died at spawn. - **pi native mode: bare `pi` gets plugin-mode compression with no launcher (#519)**: with this package installed (pi's package manager or `bili plugin install pi`), the pi manifest now loads `dist/agent/pi-native.js`, which at extension load (1) spawns the package's own proxy (`ensureProxyRunning` — ephemeral port, parent-pid watchdog = the pi process, attaches to a healthy compatible instance instead of doubling), (2) patches `globalThis.fetch` to rewrite model-API requests to `/bili/` (verified end-to-end: pi's SDK stack resolves fetch from the global at first-request client construction, so a load-time patch always wins; SSE streams pass through untouched; a proxy death mid-session triggers one respawn + retry), and (3) exports the existing `createBiliPlugin` factory with `BILLION_CONTEXT_PROXY` set — tools, `x-bili-plugin` headers, `/acp` and the compaction cancel all reuse the launcher-mode code paths. The patch matches only model-API URL shapes (`/v1/messages`, `(v\d+/)?chat/completions|completions|responses|conversations` suffixes — version unpinned for zhipuai `/v4/…`, path-prefixed for bailian `/apps/anthropic/v1/messages`) and never touches the proxy's own `/bili/`|`/__bili/` paths or non-HTTP(S) URLs; a failed/timeout bootstrap degrades to direct sends with a one-time warning. Opt-out: `BILI_NATIVE_PI=0`. Skipped entirely under a `bili` launch (`BILLION_CONTEXT_PROXY`/`BILI_PROVIDER_REWRITES` set) — `bili pi` keeps injecting `dist/agent/pi.js` as before. `ensureProxyRunning` gained `deps.scriptPath` (inside pi, `process.argv[1]` is pi's own script, not the package bin). Coexistence: the legacy `billion-context-pi` adapter detects the proxy via a `/bili/` baseUrl prefix or `BILLION_CONTEXT_PROXY`, both invisible under native mode (fetch-layer rewrite; env written asynchronously) — so BOTH installed used to mean double compression. `bili plugin install pi` removes the legacy entry, and the synchronous `BILLION_CONTEXT_NATIVE=pi` marker (see above) lets the standalone extension stand down at action time once it adopts the check. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index f994fbcc68..8f2a55e13b 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -115,6 +115,16 @@ Top-level keys that control how the proxy listens and behaves globally. - **Description:** Global wire-compat role map. `roles` maps message roles to the role name your upstream accepts, e.g. `{"compat":{"roles":{"developer":"system"}}}` rewrites `developer` → `system` on the final forwarded body for upstreams that reject the `developer` role (#552, newer codex clients). Applies to `openai` chat-completions and `responses` requests; exact-match roles only, everything else in the body is untouched; re-sent compress-retry bodies carry the same rewrite. Per-provider `compat.roles` entries (see [Providers](#providers)) win per key. Default `{}` forwards bodies byte-for-byte unchanged. - **Learn-on-failure:** with no compat configured, an upstream `400 Invalid role: …` is auto-fixed — bili rewrites the offending role to `system`, retries once, and remembers the mapping **session-scoped** (in-memory on the session; never written to config). Later requests in that session skip the 400 round-trip. The info log emitted when the fix fires carries the permanent per-provider snippet. +### `outputSteering` + +- **Type:** `{ enabled?: boolean; verbosityLevel?: number; effortRouting?: boolean }` +- **Default:** `{ enabled: false, verbosityLevel: 2, effortRouting: true }` (OFF — zero behavior change until enabled) +- **Status:** ACTIVE +- **Description:** Output-side compression (#1093). Output tokens cost ~5× input and are billed the instant they stream out, so both levers act at request time. They run at the forward boundary **after** every other body mutation (last, after `compat.roles`), so the turn classifier sees the final wire list; compress-retry re-sends carry the same idempotent transform. All launcher / native-plugin / `/bili/` lanes inherit it automatically. + - **Verbosity steering** — appends a byte-stable conciseness directive at the **tail** of the system prompt (`verbosityLevel` L0–L4, default L2; L0 = no directive). Never prepends (that busts the prefix cache), and is **skip-if-absent** — it never fabricates a system carrier the client didn't send (a newly injected system can itself be rejected by placement-strict backends, #377 class). Idempotent: re-applying the same level is a byte-stable no-op, a level change replaces the sentinel-wrapped block in place, so retries never accumulate it. Covers all four wires: Anthropic `system` (string or block array — `cache_control` breakpoints preserved), OpenAI `system`/`developer` message, Responses `instructions`, Google `systemInstruction.parts`. + - **Effort routing** — classifies the final turn **structurally** (block composition only, no content pattern-matching). On a mechanical continuation turn (clean tool result, no error) it lowers an **already-present** effort field toward its floor: OpenAI `reasoning_effort` → `low`; Responses `reasoning.effort` → `low`; Anthropic `output_config.effort` → `low` + `thinking.budget_tokens` → 1024 (documented API floor); Google `generationConfig.thinkingConfig.thinkingBudget` → 128 (**assumed** floor — verify per-model before relying on it). Clamp-only: it never injects an effort field the client didn't send (models without effort support 400 on it), never toggles `thinking.type` (disabling thinking over a history that carries thinking blocks 400s and busts the cache tier), and leaves dynamic budgets (`-1`) and non-mechanical turns untouched. Unrecognized structural shapes are not classified (conservative — the request goes out unchanged). +- A per-provider `providers..outputSteering` replaces this global block for that route (see [Providers](#providers)). + ### `proxy` - **Type:** `string` @@ -195,6 +205,13 @@ A shallow key (`https://open.bigmodel.cn`) matches every path on that host. A de - **Status:** ACTIVE - **Description:** Per-provider wire-compat overrides. `roles` maps message roles to the role name this upstream accepts, e.g. `{"developer": "system"}` for upstreams that reject the `developer` role newer codex clients send (#552). Applied to the final forwarded `openai`/`responses` body — client-sent roles and bili's own injected prompt alike — and to every body the compress-retry loops re-send. Wins per key over the global `compat` block (see [Server Settings](#server-settings)). Default `{}` forwards byte-for-byte unchanged. +### `outputSteering` + +- **Type:** `{ enabled?: boolean; verbosityLevel?: number; effortRouting?: boolean }` +- **Default:** *(inherits the global [`outputSteering`](#outputsteering) block)* +- **Status:** ACTIVE +- **Description:** Per-provider override of output-side compression (#1093) — verbosity steering + effort routing, see [Server Settings](#server-settings) for the two levers and their safety rules. Replaces the global block for this route rather than merging field-by-field: e.g. enable steering globally but keep one route untouched with `{"enabled": false}`, or run a different level on a specific upstream. Fields omitted inside a route entry fall back to the built-in defaults (`verbosityLevel: 2`, `effortRouting: true`), not to the global values. + ### `passthrough` - **Type:** `boolean` diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 0631f4405f..3b271a2ef5 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -115,6 +115,16 @@ - **说明:** 全局线上兼容角色映射。`roles` 把消息角色映射为上游接受的角色名,例如 `{"compat":{"roles":{"developer":"system"}}}` 把 `developer` → `system`,用于拒绝 `developer` 角色的上游(#552,新版 codex 客户端会发送)。作用于 `openai` chat-completions 与 `responses` 请求;仅精确匹配角色,体内其它内容不动;压缩重试重发的请求体同样携带。按 provider 的 `compat.roles`(见 [Providers](#providers))按键优先。默认 `{}` 逐字节透明转发。 - **失败自学习:** 未配置 compat 时,上游返回 `400 Invalid role: …` 会被自动修复 —— bili 把被拒角色改写为 `system`,重试一次,并把学到的映射记在**会话上**(仅内存,绝不写入配置)。该会话后续请求免 400 往返。修复生效时打印的 info 日志附带可永久化的 per-provider 片段。 +### `outputSteering` + +- **类型:** `{ enabled?: boolean; verbosityLevel?: number; effortRouting?: boolean }` +- **默认值:** `{ enabled: false, verbosityLevel: 2, effortRouting: true }`(关闭 —— 启用前零行为变化) +- **状态:** ACTIVE +- **说明:** 输出侧压缩(#1093)。输出 token 价格约为输入 token 的 5 倍,且一经流出即计费,所以两个杠杆都只能在请求时生效。二者在转发边界执行,位于所有其它 body 变更**之后**(最后,在 `compat.roles` 之后),保证轮次分类器看到的是最终 wire 列表;压缩重试重发的请求体携带同一幂等变换。launcher / native-plugin / `/bili/` 各通道自动继承。 + - **Verbosity steering(详略引导)** —— 在 system prompt **尾部**追加一段字节稳定的简洁指令(`verbosityLevel` L0–L4,默认 L2;L0 = 不加指令)。绝不前置(会破坏 prefix cache),且**缺席即跳过** —— 从不伪造客户端没发送的 system 载体(新注入的 system 本身就可能被放置严格的上游拒绝,#377 一类)。幂等:重复应用同一级别是字节级 no-op,级别变化就地替换 sentinel 包裹的块,重试不会累积。覆盖全部四种 wire:Anthropic `system`(字符串或块数组 —— `cache_control` 断点保留)、OpenAI `system`/`developer` 消息、Responses `instructions`、Google `systemInstruction.parts`。 + - **Effort routing(努力度路由)** —— 对最后一轮做**结构性**分类(只看块组成,不做内容模式匹配)。机械续轮(干净的 tool 结果、无错误)上把**已存在**的 effort 字段向地板值压低:OpenAI `reasoning_effort` → `low`;Responses `reasoning.effort` → `low`;Anthropic `output_config.effort` → `low` + `thinking.budget_tokens` → 1024(文档化 API 下限);Google `generationConfig.thinkingConfig.thinkingBudget` → 128(**假定**下限 —— 依赖前请按模型核实)。只降不注:从不注入客户端没发送的 effort 字段(不支持 effort 的模型会 400),从不切换 `thinking.type`(在携带 thinking 块的历史上禁用 thinking 会 400 并击穿缓存层),动态预算(`-1`)与非机械轮一律不动。无法识别的结构形状不做分类(保守 —— 请求原样发出)。 +- 按 provider 的 `providers..outputSteering` 对该路由整体替换此全局块(见 [Providers](#providers))。 + ### `proxy` - **类型:** `string` @@ -193,6 +203,13 @@ - **状态:** ACTIVE - **说明:** 按 provider 的线上兼容覆盖。`roles` 把消息角色映射为该上游接受的角色名,例如 `{"developer": "system"}` —— 用于拒绝 `developer` 角色的上游(#552,新版 codex 客户端会发这个角色)。作用于最终转发的 `openai`/`responses` 请求体 —— 客户端发送的角色和 bili 自己注入的提示一视同仁 —— 压缩重试循环重发的请求体同样携带该改写。按键覆盖全局 `compat` 块(见[服务端设置](#服务端设置))。默认 `{}` 逐字节透明转发。 +### `outputSteering` + +- **类型:** `{ enabled?: boolean; verbosityLevel?: number; effortRouting?: boolean }` +- **默认值:** *(继承全局 [`outputSteering`](#outputsteering) 块)* +- **状态:** ACTIVE +- **说明:** 输出侧压缩(#1093)的按 provider 覆盖 —— verbosity steering + effort routing,两个杠杆及其安全规则见[服务端设置](#server-settings)。对该路由**整体替换**全局块,而不是逐字段合并:例如全局开启 steering、用 `{"enabled": false}` 保持某个路由不受影响,或在特定上游使用不同级别。route 条目内省略的字段回落到内置默认值(`verbosityLevel: 2`、`effortRouting: true`),而非全局块的取值。 + ### `passthrough` - **类型:** `boolean` diff --git a/src/output-steering.ts b/src/output-steering.ts index da3f225228..b941c577ef 100644 --- a/src/output-steering.ts +++ b/src/output-steering.ts @@ -134,6 +134,10 @@ function classifyAnthropicTurn(messages: unknown): TurnKind { if (b.is_error === true) sawError = true; } else if (t === "text" || t === "image" || t === "document") { return "new_user_ask"; + } else { + // Unrecognized block composition: do not classify (conservative — + // an unknown block may carry user intent we cannot see). + return "unknown"; } } if (sawError) return "error_continuation"; @@ -189,27 +193,37 @@ function responsesUserSignal(item: Record): boolean { return false; } -/** Responses API: the whole `input` is a flat list of items. Mechanical means - * it carries tool-output items, no fresh user signal, and nothing unrecognized. */ +/** Responses API: the whole `input` is a flat list of items re-sent in full on + * every request. Mechanical means the FINAL turn (everything after the last + * user signal) carries tool-output items and nothing unrecognized. */ +/** Item types that may sit between the last user signal and the trailing tool + * outputs without breaking a mechanical continuation (assistant-side items: + * prose, tool calls, thinking). */ +const RESPONSES_NEUTRAL_TYPES = new Set(["message", "function_call", "custom_tool_call", "local_shell_call", "apply_patch_call", "reasoning"]); + function classifyResponsesTurn(input: unknown): TurnKind { if (typeof input === "string") return input.trim() ? "new_user_ask" : "unknown"; if (!Array.isArray(input) || input.length === 0) return "unknown"; + // Walk BACKWARD from the end: the final turn is everything after the LAST + // user signal. Clients re-send full history on every request (codex does), + // so scanning forward would hit the original ask on every turn and could + // never classify a continuation. let sawToolOutput = false; - let sawUnknown = false; - for (const raw of input) { - const item = asRecord(raw); - if (!item) { - sawUnknown = true; + for (let i = input.length - 1; i >= 0; i--) { + const item = asRecord(input[i]); + if (!item) return "unknown"; + const it = item.type; + if (typeof it === "string" && RESPONSES_OUTPUT_TYPES.has(it)) { + sawToolOutput = true; continue; } - const it = item.type; - if (typeof it === "string" && RESPONSES_OUTPUT_TYPES.has(it)) sawToolOutput = true; - else if (responsesUserSignal(item)) return "new_user_ask"; - else if (it === "message" || it === "function_call" || it === "reasoning") continue; - else sawUnknown = true; + // Hitting the last user signal: tool outputs AFTER it mean the final + // turn is a continuation; none means the user just asked something. + if (responsesUserSignal(item)) return sawToolOutput ? "mechanical_continuation" : "new_user_ask"; + if (typeof it === "string" && RESPONSES_NEUTRAL_TYPES.has(it)) continue; + return "unknown"; } - if (sawToolOutput && !sawUnknown) return "mechanical_continuation"; - return "unknown"; + return sawToolOutput ? "mechanical_continuation" : "unknown"; } /** Google native: the conversation is `contents`; a mechanical continuation is a @@ -228,8 +242,12 @@ function classifyGoogleTurn(contents: unknown): TurnKind { sawFunctionResponse = true; continue; } - if (typeof p.text === "string" && p.text.trim()) return "new_user_ask"; + if (typeof p.text === "string") { + if (p.text.trim()) return "new_user_ask"; + continue; // empty text part: neutral + } if (p.inlineData || p.fileData || p.videoMetadata) return "new_user_ask"; + return "unknown"; // unrecognized part composition: do not classify } if (sawFunctionResponse) return "mechanical_continuation"; return "unknown"; diff --git a/tests/output-steering.test.ts b/tests/output-steering.test.ts index 0c412d534d..145e7c6bce 100644 --- a/tests/output-steering.test.ts +++ b/tests/output-steering.test.ts @@ -250,3 +250,79 @@ test("applyOutputSteeringJson mutates in place and is idempotent", () => { assert.deepEqual(applyOutputSteeringJson(obj, "responses", STEER_ONLY), [], "second pass finds the block already present"); assert.ok(String(obj.instructions).includes(SENTINEL)); }); + +test("responses: full-history re-send (original ask + call + output) IS a mechanical continuation", () => { + const body = { + model: "m", + instructions: "You are Codex.", + input: [ + { type: "message", role: "user", content: [{ type: "input_text", text: "fix the bug in src/a.ts" }] }, + { type: "function_call", name: "shell", arguments: '{"cmd":"ls"}', call_id: "call_1" }, + { type: "function_call_output", call_id: "call_1", output: "file listing" }, + ], + reasoning: { effort: "high" }, + }; + const out = applyOutputSteering(JSON.stringify(body), "responses", EFFORT_ONLY); + assert.deepEqual(out.labels, ["effort:low"]); + assert.equal((JSON.parse(out.body).reasoning as { effort: string }).effort, "low"); +}); + +test("responses: codex custom_tool_call / apply_patch shapes stay mechanical", () => { + const body = { + model: "m", + input: [ + { type: "message", role: "user", content: [{ type: "input_text", text: "run the tests" }] }, + { type: "custom_tool_call", name: "shell", input: '{"cmd":"npm test"}', call_id: "c1" }, + { type: "custom_tool_call_output", call_id: "c1", output: "all pass" }, + { type: "apply_patch_call", input: "*** Begin Patch\n*** End Patch", call_id: "c2" }, + { type: "apply_patch_call_output", call_id: "c2", output: "Success." }, + ], + reasoning: { effort: "medium" }, + }; + const out = applyOutputSteering(JSON.stringify(body), "responses", EFFORT_ONLY); + assert.deepEqual(out.labels, ["effort:low"]); +}); + +test("responses: a fresh user signal at the tail blocks lowering even after outputs", () => { + const body = { + model: "m", + input: [ + { type: "message", role: "user", content: [{ type: "input_text", text: "do X" }] }, + { type: "function_call", name: "f", arguments: "{}", call_id: "c1" }, + { type: "function_call_output", call_id: "c1", output: "ok" }, + { type: "message", role: "user", content: [{ type: "input_text", text: "now do Y" }] }, + ], + reasoning: { effort: "high" }, + }; + assert.equal(applyOutputSteering(JSON.stringify(body), "responses", EFFORT_ONLY).changed, false); +}); + +test("responses: a pending call with no output yet is not a continuation", () => { + const body = { + model: "m", + input: [ + { type: "message", role: "user", content: [{ type: "input_text", text: "do X" }] }, + { type: "function_call", name: "f", arguments: "{}", call_id: "c1" }, + ], + reasoning: { effort: "high" }, + }; + assert.equal(applyOutputSteering(JSON.stringify(body), "responses", EFFORT_ONLY).changed, false); +}); + +test("anthropic: unrecognized block composition is not classified mechanical", () => { + const body = { + model: "m", + messages: [{ role: "user", content: [{ type: "tool_result", tool_use_id: "t", content: "x" }, { type: "mystery_block" }] }], + output_config: { effort: "high" }, + }; + assert.equal(applyOutputSteering(JSON.stringify(body), "anthropic", EFFORT_ONLY).changed, false); +}); + +test("google: unrecognized part composition is not classified mechanical", () => { + const body = { + model: "m", + contents: [{ role: "user", parts: [{ functionResponse: { name: "f", response: {} } }, { mystery: true }] }], + generationConfig: { thinkingConfig: { thinkingBudget: 8000 } }, + }; + assert.equal(applyOutputSteering(JSON.stringify(body), "google", EFFORT_ONLY).changed, false); +}); From 404b534454080cf2fdec5b603fee23e2c5362709 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 21 Sep 2026 23:07:50 +0800 Subject: [PATCH 3/5] fix: review follow-ups for output steering (#1093) - treat explicit minimal effort as at-floor (clamp-only invariant: never raise a client-sent minimal to low on openai/responses) - compress rounds re-send without the verbosity directive (summary fidelity: the never-restate clause contradicts the compress prompt's verbatim-preservation contract); effort routing stays - warn (instead of silently clamping) on out-of-range verbosityLevel --- src/output-steering.ts | 32 +++++++++++++++++++++++++------- src/server.ts | 25 ++++++++++++++++--------- tests/output-steering.test.ts | 23 +++++++++++++++++++++++ 3 files changed, 64 insertions(+), 16 deletions(-) diff --git a/src/output-steering.ts b/src/output-steering.ts index b941c577ef..85602fec1f 100644 --- a/src/output-steering.ts +++ b/src/output-steering.ts @@ -1,4 +1,5 @@ import type { WireProtocol } from "./util.js"; +import { log as loggerLog } from "./logger.js"; /** * Output-side compression (#1093): verbosity steering + effort routing. @@ -84,8 +85,9 @@ export const DEFAULT_OUTPUT_STEERING: OutputSteeringConfig = { effortRouting: true, }; -function clampVerbosityLevel(v: unknown): number { +function clampVerbosityLevel(v: unknown, warn: (msg: string) => void): number { if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4) return v; + warn(`[config] outputSteering.verbosityLevel must be an integer 0-4; got ${JSON.stringify(v)} — falling back to 2`); return 2; } @@ -95,11 +97,14 @@ function clampVerbosityLevel(v: unknown): number { export function parseOutputSteering(v: unknown): OutputSteeringConfig | undefined { if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; const obj = v as Record; - return { + const warnings: string[] = []; + const cfg = { enabled: obj.enabled === true, - verbosityLevel: clampVerbosityLevel(obj.verbosityLevel), + verbosityLevel: clampVerbosityLevel(obj.verbosityLevel, (m) => warnings.push(m)), effortRouting: obj.effortRouting !== false, }; + for (const w of warnings) loggerLog("warn", w); + return cfg; } // ---- Turn classification (pure structural, no content pattern-matching) ---- @@ -378,7 +383,10 @@ function lowerEffort(obj: Record, protocol: WireProtocol): bool switch (protocol) { case "openai": { const e = obj.reasoning_effort; - if (typeof e === "string" && e !== "low") { + // "minimal" sits below "low" on the OpenAI scale — a client that + // explicitly asked for it is already at/below our floor; raising it + // would override client intent (clamp-only invariant). + if (typeof e === "string" && e !== "low" && e !== "minimal") { obj.reasoning_effort = "low"; return true; } @@ -388,7 +396,8 @@ function lowerEffort(obj: Record, protocol: WireProtocol): bool const r = asRecord(obj.reasoning); if (!r) return false; const e = r.effort; - if (typeof e === "string" && e !== "low") { + // Same scale as OpenAI: "minimal" is already at/below the floor. + if (typeof e === "string" && e !== "low" && e !== "minimal") { r.effort = "low"; return true; } @@ -464,12 +473,21 @@ export function applyOutputSteering(body: string, protocol: WireProtocol | null, /** Object-level variant shared by the forward boundary and the compress-retry * re-send paths. Mutates `parsed` in place; returns the applied labels. */ -export function applyOutputSteeringJson(parsed: Record, protocol: WireProtocol | null, cfg: OutputSteeringConfig): string[] { +export interface ApplySteeringOptions { + /** Skip the verbosity directive while keeping effort routing. Used by the + * kernel's compress rounds: the L2/L3 directive ("never restate code, file + * contents, diffs, or tool output …") directly contradicts the compress + * prompt's own contract — summaries must preserve exact paths, values and + * commands verbatim because they are the primary carrier on decompress. */ + verbosity?: boolean; +} + +export function applyOutputSteeringJson(parsed: Record, protocol: WireProtocol | null, cfg: OutputSteeringConfig, opts: ApplySteeringOptions = {}): string[] { if (!cfg.enabled) return []; const proto = protocol ?? detectProtocolFromBody(parsed); if (!proto) return []; const labels: string[] = []; - if (cfg.verbosityLevel > 0 && steerSystemPrompt(parsed, proto, cfg.verbosityLevel)) { + if (opts.verbosity !== false && cfg.verbosityLevel > 0 && steerSystemPrompt(parsed, proto, cfg.verbosityLevel)) { labels.push(`steering:L${cfg.verbosityLevel}`); } if (cfg.effortRouting && classifyTurn(proto, parsed) === "mechanical_continuation" && lowerEffort(parsed, proto)) { diff --git a/src/server.ts b/src/server.ts index 619adbeb16..aab73e5f9e 100644 --- a/src/server.ts +++ b/src/server.ts @@ -3996,13 +3996,20 @@ async function forward( // are read at CALL time (a role learned / config resolved mid-request applies // to later re-sends within the same request). Steering is idempotent, so a // re-send neither accumulates the directive nor re-lowers an already-low field. - const wireTransform = compatProtocol || steerEnabled - ? (b: Record): Record => { - if (compatProtocol && compatRoles) applyCompatRolesJson(b, compatProtocol, compatRoles); - if (steerEnabled) applyOutputSteeringJson(b, wireProtocol, steerCfg); - return b; - } - : undefined; + const makeWireTransform = (withVerbosity: boolean) => + compatProtocol || steerEnabled + ? (b: Record): Record => { + if (compatProtocol && compatRoles) applyCompatRolesJson(b, compatProtocol, compatRoles); + if (steerEnabled) applyOutputSteeringJson(b, wireProtocol, steerCfg, { verbosity: withVerbosity }); + return b; + } + : undefined; + const wireTransform = makeWireTransform(true); + // Compress rounds re-send WITHOUT the verbosity directive (summary + // fidelity: the directive's "never restate paths/code" clause contradicts + // the compress prompt's verbatim-preservation contract) — compat rewrite + // and effort routing stay (see #1096 review). + const compressWireTransform = makeWireTransform(false); // Show the final proxied URL (where the request actually lands) as the // primary signal. The provider label is appended only for named routes — // zero-config requests have a single routing mode now, so the final @@ -4699,7 +4706,7 @@ async function forward( streamToRead, { core, config, messages: prepared.processedMessages.length > 0 ? prepared.processedMessages : prepared.originalMessages, compressMessages: prepared.originalMessages, session: prepared.session, log: ctx.log, proxyUrl, protocol: prepared.protocol, textProtocol, debug: opts.debug, refreshFolded, visibilityMarkers }, parsedReq, - { url: upstreamUrl, headers: reqHeaders, wireTransform }, + { url: upstreamUrl, headers: reqHeaders, wireTransform: compressWireTransform }, adapter, systemPrompt, clientAbort.signal, @@ -4752,7 +4759,7 @@ async function forward( json, { core, config, messages: prepared.originalMessages, session: prepared.session, log: ctx.log, proxyUrl, textProtocol: true, visibilityMarkers }, requestBody, - { url: upstreamUrl, headers: requestHeaders, wireTransform }, + { url: upstreamUrl, headers: requestHeaders, wireTransform: compressWireTransform }, ); } // Capture upstream usage so tokenCount (which drives nudge + diff --git a/tests/output-steering.test.ts b/tests/output-steering.test.ts index 145e7c6bce..5504c427e9 100644 --- a/tests/output-steering.test.ts +++ b/tests/output-steering.test.ts @@ -326,3 +326,26 @@ test("google: unrecognized part composition is not classified mechanical", () => }; assert.equal(applyOutputSteering(JSON.stringify(body), "google", EFFORT_ONLY).changed, false); }); + +test("openai: explicit minimal effort is never raised to low", () => { + const mech = { model: "m", messages: [{ role: "assistant", content: "", tool_calls: [{ id: "c", type: "function", function: { name: "f", arguments: "{}" } }] }, { role: "tool", tool_call_id: "c", content: "result" }], reasoning_effort: "minimal" }; + const out = applyOutputSteering(JSON.stringify(mech), "openai", EFFORT_ONLY); + assert.equal(out.changed, false, "minimal sits below the low floor — clamp must not raise it"); + assert.equal(JSON.parse(out.body).reasoning_effort, "minimal"); +}); + +test("responses: explicit minimal effort is never raised to low", () => { + const mech = { model: "m", input: [{ type: "function_call_output", call_id: "c", output: "{}" }], reasoning: { effort: "minimal" } }; + const out = applyOutputSteering(JSON.stringify(mech), "responses", EFFORT_ONLY); + assert.equal(out.changed, false, "minimal sits below the low floor — clamp must not raise it"); + assert.equal((JSON.parse(out.body).reasoning as { effort: string }).effort, "minimal"); +}); + +test("applyOutputSteeringJson opts.verbosity=false skips the directive but keeps effort routing", () => { + const obj = { model: "m", messages: [{ role: "assistant", content: "", tool_calls: [{ id: "c", type: "function", function: { name: "f", arguments: "{}" } }] }, { role: "tool", tool_call_id: "c", content: "result" }], reasoning_effort: "high" }; + const labels = applyOutputSteeringJson(obj, "openai", { enabled: true, verbosityLevel: 2, effortRouting: true }, { verbosity: false }); + assert.deepEqual(labels, ["effort:low"]); + assert.equal(obj.reasoning_effort, "low"); + const sys = obj.messages.find((m) => m.role === "system" || m.role === "developer"); + assert.equal(sys, undefined, "no steering block appended on compress rounds"); +}); From 07257c3691ce661b19ae7188768420c4cc7971a6 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 22 Sep 2026 00:09:05 +0800 Subject: [PATCH 4/5] fix: verbosity config warning fired on omitted field; drop dead transform (#1093) b8bf783 made clampVerbosityLevel warn on any non-integer-0..4 value, which includes undefined: every config that omits verbosityLevel (the documented default case) logged a false 'must be an integer 0-4' warning at load. resolveVerbosityLevel now warns only when the field is PRESENT but invalid (honest output); omitted silently takes L2. Also removes the now-unused wireTransform(true) local left behind when both compress-loop call sites moved to compressWireTransform(false), and corrects its stale comment. --- src/output-steering.ts | 21 ++++++++++++--------- src/server.ts | 13 ++++++------- tests/output-steering.test.ts | 17 +++++++++++++++++ 3 files changed, 35 insertions(+), 16 deletions(-) diff --git a/src/output-steering.ts b/src/output-steering.ts index 85602fec1f..b568ae065d 100644 --- a/src/output-steering.ts +++ b/src/output-steering.ts @@ -85,10 +85,14 @@ export const DEFAULT_OUTPUT_STEERING: OutputSteeringConfig = { effortRouting: true, }; -function clampVerbosityLevel(v: unknown, warn: (msg: string) => void): number { - if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4) return v; - warn(`[config] outputSteering.verbosityLevel must be an integer 0-4; got ${JSON.stringify(v)} — falling back to 2`); - return 2; +/** Resolve verbosityLevel. An OMITTED field silently takes the default; a + * PRESENT but out-of-range value falls back WITH a warning (honest output — + * a valid partial config must not be accused of being malformed). */ +export function resolveVerbosityLevel(v: unknown): { level: number; warning?: string } { + if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4) return { level: v }; + const level = DEFAULT_OUTPUT_STEERING.verbosityLevel; + if (v === undefined) return { level }; + return { level, warning: `[config] outputSteering.verbosityLevel must be an integer 0-4; got ${JSON.stringify(v)} — falling back to ${level}` }; } /** Validate an `outputSteering`-shaped value. Malformed fields fall back to @@ -97,14 +101,13 @@ function clampVerbosityLevel(v: unknown, warn: (msg: string) => void): number { export function parseOutputSteering(v: unknown): OutputSteeringConfig | undefined { if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; const obj = v as Record; - const warnings: string[] = []; - const cfg = { + const lvl = resolveVerbosityLevel(obj.verbosityLevel); + if (lvl.warning) loggerLog("warn", lvl.warning); + return { enabled: obj.enabled === true, - verbosityLevel: clampVerbosityLevel(obj.verbosityLevel, (m) => warnings.push(m)), + verbosityLevel: lvl.level, effortRouting: obj.effortRouting !== false, }; - for (const w of warnings) loggerLog("warn", w); - return cfg; } // ---- Turn classification (pure structural, no content pattern-matching) ---- diff --git a/src/server.ts b/src/server.ts index aab73e5f9e..e5179331e0 100644 --- a/src/server.ts +++ b/src/server.ts @@ -3990,12 +3990,12 @@ async function forward( } } // #552/#1093: wire transform shared by ALL re-send paths (compress-retry - // loops below) so re-sent bodies carry the same rewrite AND steering as the - // initial forward — otherwise a developer-role 400 would hit mid-stream on - // the first retry, or a retry would drop the directive/effort change. Both - // are read at CALL time (a role learned / config resolved mid-request applies - // to later re-sends within the same request). Steering is idempotent, so a - // re-send neither accumulates the directive nor re-lowers an already-low field. + // loops below) so re-sent bodies carry the same compat rewrite and effort + // routing as the initial forward — otherwise a developer-role 400 would hit + // mid-stream on the first retry, or a retry would drop the effort change. + // Both are read at CALL time (a role learned / config resolved mid-request + // applies to later re-sends within the same request). The transform is + // idempotent, so a re-send never double-applies. const makeWireTransform = (withVerbosity: boolean) => compatProtocol || steerEnabled ? (b: Record): Record => { @@ -4004,7 +4004,6 @@ async function forward( return b; } : undefined; - const wireTransform = makeWireTransform(true); // Compress rounds re-send WITHOUT the verbosity directive (summary // fidelity: the directive's "never restate paths/code" clause contradicts // the compress prompt's verbatim-preservation contract) — compat rewrite diff --git a/tests/output-steering.test.ts b/tests/output-steering.test.ts index 5504c427e9..cdb8a4c080 100644 --- a/tests/output-steering.test.ts +++ b/tests/output-steering.test.ts @@ -5,6 +5,7 @@ import { applyOutputSteering, applyOutputSteeringJson, parseOutputSteering, + resolveVerbosityLevel, steeringText, type OutputSteeringConfig, } from "../src/output-steering.ts"; @@ -349,3 +350,19 @@ test("applyOutputSteeringJson opts.verbosity=false skips the directive but keeps const sys = obj.messages.find((m) => m.role === "system" || m.role === "developer"); assert.equal(sys, undefined, "no steering block appended on compress rounds"); }); + +test("resolveVerbosityLevel: omitted field takes default WITHOUT warning", () => { + assert.deepEqual(resolveVerbosityLevel(undefined), { level: DEFAULT_OUTPUT_STEERING.verbosityLevel }); +}); + +test("resolveVerbosityLevel: valid levels 0-4 pass through untouched", () => { + for (const n of [0, 1, 2, 3, 4]) assert.deepEqual(resolveVerbosityLevel(n), { level: n }); +}); + +test("resolveVerbosityLevel: present-but-invalid values warn and fall back", () => { + for (const bad of [9, -1, 2.5, "high", null]) { + const r = resolveVerbosityLevel(bad); + assert.equal(r.level, DEFAULT_OUTPUT_STEERING.verbosityLevel); + assert.ok(r.warning?.includes("must be an integer 0-4"), `expected warning for ${JSON.stringify(bad)}, got ${r.warning}`); + } +}); From 1986ffc20b5a1cd24cc60bf731055960cab0d79e Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 23 Sep 2026 16:16:07 +0800 Subject: [PATCH 5/5] =?UTF-8?q?docs:=20steering=20regression-test=20count?= =?UTF-8?q?=2029=20=E2=86=92=2035=20(#1093)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a07e51dce5..ea8ec4756f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag - **Output-side compression: verbosity steering + effort routing (#1093)**: ports headroom's two output-token levers to bili's forward boundary. Output tokens cost ~5× input and are billed the instant they stream out, so the only lever is at request time. Both levers are **default off** (zero behavior change until enabled) and run LAST at the forward boundary — after every other body mutation, after `compat.roles` — so the turn classifier sees the final wire list; compress-retry re-sends share the same idempotent transform (`wireTransform`), and launcher / native-plugin / `/bili/` lanes inherit automatically. When disabled the path is byte-identical (no parse, no re-serialize). - *Verbosity steering* appends a byte-stable conciseness directive (levels L0–L4, default L2) at the **tail** of the system prompt. Never prepends (that busts the prefix cache); **skip-if-absent** — it never fabricates a system carrier the client didn't send (a newly injected system can itself be rejected by placement-strict backends, #377 class); sentinel-wrapped and idempotent — re-applying the same level is a byte-stable no-op, a level change replaces the block in place, so retries never accumulate it. Covers all four wires: Anthropic `system` (string + block array, `cache_control` breakpoints preserved), OpenAI `system`/`developer` message, Responses `instructions`, Google `systemInstruction.parts`. - *Effort routing* classifies the final turn **structurally** (block composition only, no content pattern-matching) and, on a mechanical continuation turn (clean tool result, no error), lowers an **already-present** effort field toward its floor: OpenAI `reasoning_effort`→`low`; Responses `reasoning.effort`→`low`; Anthropic `output_config.effort`→`low` + `thinking.budget_tokens`→1024 (documented API floor); Google `generationConfig.thinkingConfig.thinkingBudget`→128 (**assumed** floor, documented as such). Clamp-only safety rules: never injects an effort field the client didn't send (models without effort support 400 on it), never toggles `thinking.type` (disabling thinking over a history that carries thinking blocks 400s and busts the cache tier), dynamic budgets (`-1`) and non-mechanical turns untouched, unrecognized structural shapes not classified (conservative — request goes out unchanged). The Responses classifier walks the flat `input` list BACKWARD from the tail: clients re-send full history every request (codex does), so a forward scan would hit the original ask on every turn and could never classify a continuation; assistant-side items between the last user signal and the trailing tool outputs (`message`, `function_call`, `custom_tool_call`, `local_shell_call`, `apply_patch_call`, `reasoning`) do not break the continuation. - - Config: `billion-context.json` `outputSteering` block (global + per-provider route overlay, same shape as `compat`). 29 regression tests across all four wires (idempotency, skip-if-absent, clamp-only rules, full-history continuation classification). + - Config: `billion-context.json` `outputSteering` block (global + per-provider route overlay, same shape as `compat`). 35 regression tests across all four wires (idempotency, skip-if-absent, clamp-only rules, full-history continuation classification). - **Coexistence marker for standalone extensions (#820)**: the pi-native and opencode-native entries now set `BILLION_CONTEXT_NATIVE=` synchronously at module evaluation (gated on their own bootstrap gate, first writer wins — `markNativeHost()` in `src/agent/native-bootstrap.ts`), so the standalone `billion-context-pi` / `opencode-acp` extensions can stand down at action time when running alongside a native entry. Verified against both sibling repos that the pre-existing auto-disable does NOT cover native mode: they check `BILLION_CONTEXT_PROXY` only at extension-load time (native bootstrap writes it asynchronously, after the proxy is up) and detect `/bili/` in the configured baseUrl (native rewrites at the fetch layer, invisible to config); launcher mode and manual wiring keep working as before. Standalone-side adoption of the marker is tracked in each repo's issue tracker. - **opencode 2.x native mode: package-installed opencode gets plugin-mode compression with no launcher (#820, npm-package design #809)**: `bili plugin install opencode` now installs, alongside the MCP shell (kept, but optional — a missing live proxy origin skips it instead of failing the install), a self-spawning native plugin: a stable wrapper directory `/plugins/billion-context/index.js` re-exporting `dist/agent/opencode-native.js` (OpenCode 2.x rejects bare FILE paths in `plugin` — the directory's index.js is the entrypoint, #754 probe) plus `compaction.auto=false` (single compression owner; merge-preserving, restored from the `.bili-bak` backup on remove). At plugin load the same gate as pi-native applies (`BILI_NATIVE_OPENCODE=0` opt-out; skipped entirely under a `bili` launch) and the package's own proxy is bootstrapped through `ensureProxyRunning` (attach-or-spawn, ephemeral port, parent-pid watchdog, `deps.scriptPath`). OpenCode plugins have no fetch seam to patch, so egress interception uses the `http.request` hook, replacing the outgoing fetch Request REFERENCE with `new Request("/bili/", old)` carrying method/headers/body (WHATWG Request.url is read-only at runtime — verified live, #810). Header stamping, native tools and compaction-boundary reporting reuse the shared V2 setup factory (`src/agent/opencode-v2.ts`, extracted from opencode.ts so launcher mode and native mode share ONE protocol implementation). Because an http.request hook cannot observe send failures (the host swallows them), every request liveness-probes `/__bili/health` of the current origin before routing — one respawn if the proxy died mid-session, direct send + one-time warning when no origin can be made healthy (auto-recovering: each request re-verifies, unlike pi's lifetime latch). Also fixes #819: `ensureProxyRunning` resolves the Node executable for spawning via `resolveNodeRuntime()` (live Node wins → `BILLION_CONTEXT_NODE` override → PATH search) instead of blind `process.execPath`, which inside a host binary (opencode/pi native) is the HOST executable — the spawned proxy died at spawn.