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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions kernel/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions scripts/live-files.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ export const LIVE_FILES = [
// band (preload-zone-slot), so mid-list inserts renumber every later band
"tests/storage-durability.test.ts",
"tests/server-close-all-connections.test.ts",
// both spawn the corrupt-index-child helper (unified-store cold-load
// corruption probes, #4216/#4249 follow-ups); append-only per the note above
"tests/storage-engine-proofs.test.ts",
"tests/web-storage-banner.test.ts",
];

/** Band width per live file: the zone ladder drifts +1 per EADDRINUSE retry;
Expand Down
19 changes: 18 additions & 1 deletion src/server/lane-decisions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,15 @@ interface LaneDecisionInput {
readonly parsed: unknown;
/** injectTool config (`shouldInject`) — the config-level master switch. */
readonly shouldInject: boolean;
/** TRUE when THIS request carries the plugin lane header (`x-bili-plugin`),
* false when a sticky plugin-bound session serves a headerless round.
* Undefined = caller could not observe (matrix tests, legacy callers) —
* never triggers the zombie clause below. #2155/#4344 boundary: an idle
* bridge sends the header but no ACP tools (surface may go silent); a
* zombie round sends NO header at all because the plugin is gone (client
* uninstalled/crashed) — those rounds must keep the nudge/self-heal
* probe alive or degrade-to-proxy can never fire. */
readonly pluginHeaderPresent?: boolean;
}
// ④ nudgeOn — the ONE nudge-injection gate (#3482 Step 2.5). The four
// prepares used to carry four hand-copied conjunctions that drifted (#3293:
Expand Down Expand Up @@ -256,7 +265,15 @@ export function resolveLaneDecisions(input: LaneDecisionInput): LaneDecisions {
|| declaredTools.has("compress")
|| declaredTools.has(mcpBiliToolName("compress"))
|| [...CODE_MODE_OMNIBUS_TOOL_NAMES].some((n) => declaredTools.has(n))
|| !profile.toolsHostScopedByDefault;
|| !profile.toolsHostScopedByDefault
// #2155: a sticky plugin-bound round with NO lane header is the zombie
// shape (plugin gone from the client). The nudge channel doubles as
// the self-heal probe — suppressing it here starves zombieStreak and
// degrade-to-proxy never fires (#4372's zcode profile did exactly
// that). Headerless rounds keep the surface ON so the probe runs;
// once degraded, proxy tool injection replaces the lane anyway.
// (#4344's silent-bridge case always sends the header — unaffected.)
|| (input.pluginMode && input.pluginHeaderPresent === false);
const compressSurfaceOn = input.shouldInject && compressReachable;
const mcpDialect = input.pluginMode && declaredTools.has(mcpBiliToolName("compress")) && !declaredTools.has("compress");
const billingBlockObserved = extractBillingAttributionBlock(systemOf(input.parsed)) !== undefined;
Expand Down
2 changes: 2 additions & 0 deletions src/server/prepare-anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { rewriteInboundThreadContinue } from "./thread-tracking.js";
import { captureThreadsTurn, estimateThreadsTokens, isThreadsBody, threadsReforgeEnabled } from "./threads-lane.js";
import type { CompressReasoningConfig } from "../reasoning-drop.js";
import type { ProxyOptions } from "../config.js";
import { pluginAgentHeader } from "../plugin.js";
import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, reapOrphansLogged, runNudgeDecision, stripKernelSummaries, warnAnthropicThinkingPairs, type Prepared } from "../server.js";
import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js";
import { excludeDeadRefRanges } from "../acp-status.js";
Expand Down Expand Up @@ -71,6 +72,7 @@ export async function prepareAnthropic(
pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined,
parsed,
shouldInject: opts.compress.injectTool,
pluginHeaderPresent: pluginAgentHeader(req.headers) !== undefined,
});
// #3222: #651's reasoning-drop plan, computed on the INBOUND history before
// core.processTurn — see planReasoningDrop for why the post-turn view is too late.
Expand Down
3 changes: 2 additions & 1 deletion src/server/prepare-google.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { CompressionCore, Config, CoreMessage, NudgeDecision, PackSurface,
import { renderNudgeText, viableRanges } from "acp-kernel";
import { coreToGoogle, googleToCore, normalizeGoogleUserPartOrder, type BiliMessage, type GoogleContent, type GoogleRequestBody, type GoogleSystemInstruction, type GoogleTool } from "acp-kernel/wire";
import type { ProxyOptions } from "../config.js";
import { pluginAgentHeader } from "../plugin.js";
import { currentCalibrationFactor } from "../util.js";
import { diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, usageGradeInputBaseline, type Prepared } from "../server.js";
import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js";
Expand Down Expand Up @@ -101,7 +102,7 @@ export async function prepareGoogle(
const injectTools = shouldInject && !pluginMode;
// #3417: surface gating lives in lane-decisions (observed reachability
// overrides the dsh default, #3401); alias kept for the remaining reads.
const laneDecisions = resolveLaneDecisions({ protocol: "google", pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject });
const laneDecisions = resolveLaneDecisions({ protocol: "google", pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject, pluginHeaderPresent: pluginAgentHeader(req.headers) !== undefined });
// #2483: this lane used to ignore renderNone entirely (hardcoded "text-only"
// in processTurn, Prepared and countTokens) — the knob was dead config on /v1beta.
const renderStrategy = knobRenderNone() ? "none" : "text-only";
Expand Down
3 changes: 2 additions & 1 deletion src/server/prepare-openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { CompressReasoningConfig } from "../reasoning-drop.js";
import type { ProxyOptions } from "../config.js";
import { currentCalibrationFactor, hardenOpenaiAssistantContent, systemToUser } from "../util.js";
import { conversationHeaderSource, resolveRelayAffinityPck } from "../session-id.js";
import { pluginAgentHeader } from "../plugin.js";
import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, warnDroppedOpenaiParts, warnReasoningPairs, type Prepared } from "../server.js";
import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js";
import { excludeDeadRefRanges } from "../acp-status.js";
Expand Down Expand Up @@ -95,7 +96,7 @@ export async function prepareOpenai(
// keep it — their extensions expose the tools to the agent.
// #3417: that judgement now lives in lane-decisions (observed reachability
// overrides the dsh default — #3401); alias kept for the remaining reads.
const laneDecisions = resolveLaneDecisions({ protocol: "openai", pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject });
const laneDecisions = resolveLaneDecisions({ protocol: "openai", pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject, pluginHeaderPresent: pluginAgentHeader(req.headers) !== undefined });

const markerCounts = stripRawStage(parsed, "openai");
logRawStripCounts(markerCounts, log, sessionId);
Expand Down
3 changes: 2 additions & 1 deletion src/server/prepare-responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { applyImageRescaleItems } from "../image-rescale.js";
import { clampOutgoingOutput, countLoadedToolTokens, countSystemAndToolsTokens, dshLedgerFloorTokens, emergencyNudge, emergencyNudgeArmed, modelVisibleTools } from "./budget.js";
import { FORCE_TEXT_PROTOCOL, injectResponsesTool, injectTool } from "./inject.js";
import { nudgeOn, resolveLaneDecisions, surfaceOffDetail } from "./lane-decisions.js";
import { pluginAgentHeader } from "../plugin.js";

export async function prepareResponses(
parsed: ResponsesRequestBody,
Expand Down Expand Up @@ -127,7 +128,7 @@ export async function prepareResponses(
const injectTools = shouldInject && !pluginMode;
// #3417: surface gating lives in lane-decisions (observed reachability
// overrides the dsh default, #3401).
const laneDecisions = resolveLaneDecisions({ protocol: "responses", pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject });
const laneDecisions = resolveLaneDecisions({ protocol: "responses", pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject, pluginHeaderPresent: pluginAgentHeader(req.headers) !== undefined });
// Effective gate for the standing prompt + nudge: DSH reads as injectTool-off so it takes the same
// stable tags-only developer slot as any non-injecting session (prefix cache stays append-stable).
const compressSurfaceOn = laneDecisions.compressSurfaceOn;
Expand Down
8 changes: 4 additions & 4 deletions tests/corrupt-index-child.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export function makeOpts(upstreamPort: number): ProxyOptions {
// sides reference these constants, so the coverage list cannot drift.
// ---------------------------------------------------------------------------

export const ENGPROOF_CHECK_NAMES = {
const ENGPROOF_CHECK_NAMES = {
fallbackRead: "legacy fallback returned a session over the corrupt index",
midFlowGuard: "no live handle after the corrupt-index read (#2781 rename guard)",
stateDigest: "corrupt-index fallback state digest matches the clean full-mode read",
Expand All @@ -135,7 +135,7 @@ export const ENGPROOF_CHECK_NAMES = {
} as const;
export const ENGPROOF_CHECKS: readonly string[] = Object.values(ENGPROOF_CHECK_NAMES);

export const BANNER_CHECK_NAMES = {
const BANNER_CHECK_NAMES = {
overviewAnswers: "/__bili/overview answers 200 with JSON",
requestedFull: "storage.requested is full",
effectiveLegacy: "storage.effective is legacy",
Expand All @@ -146,12 +146,12 @@ export const BANNER_CHECK_NAMES = {
} as const;
export const BANNER_CHECKS: readonly string[] = Object.values(BANNER_CHECK_NAMES);

export interface CorruptIndexCheck {
interface CorruptIndexCheck {
name: string;
ok: boolean;
detail?: string;
}
export interface CorruptIndexVerdict {
interface CorruptIndexVerdict {
ok: boolean;
failure: string | null;
checks: CorruptIndexCheck[];
Expand Down
16 changes: 12 additions & 4 deletions tests/lane-decisions-matrix.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,10 +170,10 @@ async function harness(wire: Wire, lane: Lane, toolNames: string[], injectTool =
};
};
const endpoint = wire === "anthropic" ? "/v1/messages" : wire === "openai" ? "/v1/chat/completions" : wire === "responses" ? "/v1/responses" : "/v1beta/models/model-test:generateContent";
const send = async (texts: string[]) => {
const send = async (texts: string[], opts?: { headerless?: boolean }) => {
const r = await fetch(`${origin}/bili/${upstreamUrl}${endpoint}`, {
method: "POST",
headers: { "content-type": "application/json", "x-acp-session": `lane-${lane}-${toolNames.join("-") || "notools"}`, ...(lane === "proxy" ? {} : { "x-bili-plugin": lane }) },
headers: { "content-type": "application/json", "x-acp-session": `lane-${lane}-${toolNames.join("-") || "notools"}`, ...(lane === "proxy" || opts?.headerless ? {} : { "x-bili-plugin": lane }) },
body: JSON.stringify(buildBody(texts)),
});
const bodyText = await r.text();
Expand Down Expand Up @@ -228,7 +228,7 @@ function outcome(wire: Wire, sentCount: number, forwarded: Record<string, unknow
return { nudge, standingPrompt: sys.includes(STANDING_MARKER) };
}

const ROWS: { name: string; lane: Lane; tools: string[]; injectTool?: boolean; teach?: number; expect: (w: Wire) => RowOutcome }[] = [
const ROWS: { name: string; lane: Lane; tools: string[]; injectTool?: boolean; teach?: number; headerlessProbe?: boolean; expect: (w: Wire) => RowOutcome }[] = [
{ name: "omp control keeps the surface", lane: "omp", tools: [], expect: () => ({ nudge: true, standingPrompt: true }) },
{ name: "dsh no-tools drops the surface (#3177)", lane: "dsh", tools: [], expect: () => ({ nudge: false, standingPrompt: false }) },
// #3401 FIX ROW: dsh with compress actually declared on
Expand Down Expand Up @@ -290,6 +290,14 @@ const ROWS: { name: string; lane: Lane; tools: string[]; injectTool?: boolean; t
{ name: "zcode mcp__bili__compress keeps the surface (#4344 dialect-aware reachability)", lane: "zcode", tools: ["mcp__bili__compress", "mcp__bili__acp_status"], expect: () => ({ nudge: true, standingPrompt: true }) },
{ name: "zcode bare compress keeps the surface (#4344 observed declaration)", lane: "zcode", tools: ["compress", "get_weather"], expect: () => ({ nudge: true, standingPrompt: true }) },
{ name: "zcode single regular tool still drops the surface (precision retained)", lane: "zcode", tools: ["get_weather"], expect: () => ({ nudge: false, standingPrompt: false }) },
// #2155 FIX ROW: the sticky zcode session serves a HEADERLESS round (the
// zombie shape — plugin gone from the client, session still bound). The
// nudge channel doubles as the self-heal probe: #4372's host-scoped zcode
// profile read these rounds as unreachable and starved zombieStreak, so
// degrade-to-proxy never fired (issue2155-self-heal red on master). A
// headerless plugin-bound round keeps the surface ON; the #4344 silent
// bridge (header PRESENT, tools empty — row above) keeps going silent.
{ name: "zcode headerless zombie round keeps the surface (#2155 probe must stay armed)", lane: "zcode", tools: [], headerlessProbe: true, expect: () => ({ nudge: true, standingPrompt: true }) },
// Dialect reachability is lane-independent: any host-scoped lane whose
// wire carries the MCP-prefixed compress reads reachable, same as #3401's
// bare-name observation on dsh.
Expand All @@ -302,7 +310,7 @@ for (const wire of ["anthropic", "openai", "responses", "google"] as const) {
const h = await harness(wire, row.lane, row.tools, row.injectTool, row.teach);
try {
await h.send(["hello"]); // teach usage 50k / 64k = 78%
await h.send(historyTexts()); // arm the nudge
await h.send(historyTexts(), { headerless: row.headerlessProbe === true }); // arm the nudge
assert.equal(h.forwarded.length, 2, "both turns forwarded");
const got = outcome(wire, historyTexts().length, h.forwarded[1]!);
const want = row.expect(wire);
Expand Down
Loading