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
24 changes: 24 additions & 0 deletions src/compress-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,30 @@ export function withProjectAttribution(prompt: string): string {
return prompt + "\n\n" + PROJECT_ATTRIBUTION_LINE;
}

/** The MCP-dialect name bili's fixed "bili" shim server (src/mcp.ts, #2578)
* exposes an ACP tool under on MCP-bridged hosts: zcode/claude-code lanes
* carry `mcp__bili__compress` etc. in their outbound tool tables. */
export function mcpBiliToolName(name: string): string {
return "mcp__bili__" + name;
}

/** #4344: MCP-bridged plugin hosts expose the ACP tools under mcp__bili__*
* names while the kernel prompts teach the bare names — the nudge/standing
* prompt telling the model to call `compress` lands on a tool table that
* holds no such tool (the #4344 zcode shape: nudges armed at 21-29% usage,
* 0 compressions across 46 requests). When the wire declares the prefixed
* compress and NOT the bare one, this factual name mapping is appended so
* the model can act on the prompt (a bare-name call would hit an unknown
* tool — the MCP tool call routes through the host's MCP bridge, which bili
* cannot rewrite in plugin mode). Static string + per-session-stable tool
* table = cache-stable, the same premise the surface flag itself rides
* (#3403). */
export const MCP_DIALECT_NOTE = "On this host the context-management tools are exposed under MCP-prefixed names: call `mcp__bili__compress` (not `compress`) — likewise `mcp__bili__decompress`, `mcp__bili__search_context`, `mcp__bili__acp_status`.";

export function withMcpDialectNote(prompt: string, on: boolean): string {
return on ? `${prompt}\n\n${MCP_DIALECT_NOTE}` : prompt;
}

/** Note mode for one request: the harness is code-mode-shaped when the
* client's own tools array carries a tool named like a known code-mode
* omnibus (run_code / code_run — see CODE_MODE_OMNIBUS_TOOL_NAMES, #3884). */
Expand Down
11 changes: 11 additions & 0 deletions src/host-profiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,17 @@ export interface HostProfile {

const PROFILES: Record<string, HostProfile> = {
dsh: { identity: "dsh", toolsHostScopedByDefault: true, wantsBillingBlock: true, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: true },
// #4344: zcode reaches the ACP tools ONLY through its MCP bridge
// (mcp__bili__* names), and bridge delivery is environmental — zcode's
// agent modes gate MCP tools, and the degraded shim path serves an EMPTY
// tool list when no healthy proxy is found (src/zcode/mcp-entry.ts
// serveDegraded). So reachability is OBSERVED per request, never assumed:
// a healthy bridge declares mcp__bili__compress (dialect-aware, #4344
// fix) and the surface stays on; a broken/idle bridge declares nothing
// and the surface goes silent instead of advertising a tool the model
// cannot call (the #4344 shape: nudges armed at 21-29% usage, 0
// compressions — #3177's "unknown tool" discipline, applied to zcode).
zcode: { identity: "zcode", toolsHostScopedByDefault: true, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: false },
pi: { identity: "pi", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: false },
omp: { identity: "omp", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: true, coworkTransportPossible: true, instructionsFingerprintKeyed: false, compactsClientSide: false },
opencode: { identity: "opencode", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: false },
Expand Down
5 changes: 5 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1554,6 +1554,11 @@ export type Prepared = {
* response must pass through verbatim, and usage is sniffed instead of
* captured by the compress loop. */
pluginMode?: boolean;
/** #4344: this request declared the compress tool ONLY in the MCP dialect
* (mcp__bili__compress, no bare `compress`) — the prepared standing
* prompt carries the MCP name-mapping note (withMcpDialectNote). Threads
* to the round-2 system rebuild for byte-parity. */
mcpDialectNote?: boolean;
responsesTextProtocol?: boolean;
resetAfterSuccess?: boolean;
responsesProjection?: ResponsesProjection;
Expand Down
5 changes: 3 additions & 2 deletions src/server/inject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { ProxyOptions } from "../config.js";
import { type AnthropicRequestBody, type GoogleFunctionDeclaration, type GoogleTool, type OpenAITool } from "acp-kernel/wire";
import { appendSystemText } from "../util.js";
import { absorbEnabled, absorbToolName } from "../absorb.js";
import { BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE, BILI_ACP_TOOLS_GOOGLE, BILI_ACP_TOOLS_GOOGLE_NO_RANGE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_OPENAI_NO_RANGE, BILI_ACP_TOOLS_RESPONSES, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, packOwnsDescription, ptcNoteMode, withAcpNotes, withAcpNotesOpenAI, withMarkerIntegrityNote, withSummaryBudgetNote, withProjectAttribution } from "../compress-tool.js";
import { BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE, BILI_ACP_TOOLS_GOOGLE, BILI_ACP_TOOLS_GOOGLE_NO_RANGE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_OPENAI_NO_RANGE, BILI_ACP_TOOLS_RESPONSES, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, packOwnsDescription, ptcNoteMode, withAcpNotes, withAcpNotesOpenAI, withMarkerIntegrityNote, withMcpDialectNote, withSummaryBudgetNote, withProjectAttribution } from "../compress-tool.js";
import { externalSummaryEnabled, withExternalSummaryTools } from "../external-summary-surface.js";
import { forceTextProtocol as knobForceTextProtocol, renderNone as knobRenderNone } from "../knobs.js";

Expand All @@ -16,13 +16,14 @@ export function injectSystem(
surface?: PackSurface,
visibilityMarkers = true,
suppressCompressPrompt = false,
mcpDialectNote = false,
): string | AnthropicRequestBody["system"] {
// ONLY the static compress prompt goes into the system block — it is the
// prefix-cache anchor and must stay byte-stable across turns. The nudge
// (which changes every turn) is appended as a trailing user message by
// the caller (prepareAnthropic), never merged into system.
const parts: string[] = [];
if (opts.compress.injectTool && !suppressCompressPrompt) parts.push(withProjectAttribution(withMarkerIntegrityNote(withSummaryBudgetNote(buildCompressSystemPrompt(prompts, surface?.promptSections), externalSummaryEnabled(config)), visibilityMarkers)));
if (opts.compress.injectTool && !suppressCompressPrompt) parts.push(withProjectAttribution(withMcpDialectNote(withMarkerIntegrityNote(withSummaryBudgetNote(buildCompressSystemPrompt(prompts, surface?.promptSections), externalSummaryEnabled(config)), visibilityMarkers), mcpDialectNote)));
else if (!knobRenderNone()) {
// #1881: the NEVER-echo prohibition follows the rendered tags, not the tool switch.
const tagsOnly = buildAcpTagsOnlyPrompt("function", prompts, surface?.promptSections);
Expand Down
21 changes: 17 additions & 4 deletions src/server/lane-decisions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import { biliToolsDeclaredOnWire } from "../session-self-heal.js";
import { extractBillingAttributionBlock } from "../preflight.js";
import { ANONYMOUS, hostProfileFor, type HostProfile } from "../host-profiles.js";
import { CODE_MODE_OMNIBUS_TOOL_NAMES } from "../compress-tool.js";
import { CODE_MODE_OMNIBUS_TOOL_NAMES, mcpBiliToolName } from "../compress-tool.js";

type LaneProtocol = "anthropic" | "openai" | "google" | "responses";

Expand Down Expand Up @@ -154,6 +154,12 @@ interface LaneDecisions {
/** Legacy alias kept for the four prepares' migration: TRUE when the
* surface must be OFF (the old `dshCompressSurfaceOff` variable). */
readonly compressSurfaceOff: boolean;
/** #4344: this plugin-mode request declares the compress tool ONLY in the
* MCP dialect (`mcp__bili__compress`, no bare `compress`) — the standing
* prompt must teach the model the name it can actually call (see
* withMcpDialectNote). False in proxy mode (bili injects the bare tools
* itself, so the bare name is always callable). */
readonly mcpDialect: boolean;
/** #3482 site 1: should this lane's summary side-calls carry the billing
* attribution block extracted from the client system (#2189)? The dsh
* profile declares it (subscription-OAuth lanes 429 without it); any
Expand Down Expand Up @@ -232,9 +238,13 @@ export function resolveLaneDecisions(input: LaneDecisionInput): LaneDecisions {
// In PLUGIN mode the host owns the tool table: reach when this request
// declares `compress` (observed — some dsh profiles DO surface it, #3401)
// or the host exposes bili tools to the model by design (profile default,
// #3177). PTC presets collapse EVERY tool into a single omnibus (SDK
// bindings nested inside it), so top-level absence of `compress` is not
// evidence of unreachability there — ANY known omnibus name reads as
// #3177). #4344: the declaration counts in EITHER dialect — MCP-bridged
// hosts (zcode/claude-code) carry `mcp__bili__compress`, and a lane whose
// bridge is healthy must not read as unreachable just because the name is
// prefixed (session-self-heal's biliToolsDeclaredOnWire docs the same
// dual dialect). PTC presets collapse EVERY tool into a single omnibus
// (SDK bindings nested inside it), so top-level absence of `compress` is
// not evidence of unreachability there — ANY known omnibus name reads as
// reachable. Known shapes live in CODE_MODE_OMNIBUS_TOOL_NAMES (run_code
// = dsh-tools built-in, DSH 0.1.x; code_run = dsh-codemode transport,
// DSH 0.2.x): #3600's miss was released 0.1.198 suppressing the surface
Expand All @@ -244,9 +254,11 @@ export function resolveLaneDecisions(input: LaneDecisionInput): LaneDecisions {
// threshold, fully silent).
const compressReachable = !input.pluginMode
|| declaredTools.has("compress")
|| declaredTools.has(mcpBiliToolName("compress"))
|| [...CODE_MODE_OMNIBUS_TOOL_NAMES].some((n) => declaredTools.has(n))
|| !profile.toolsHostScopedByDefault;
const compressSurfaceOn = input.shouldInject && compressReachable;
const mcpDialect = input.pluginMode && declaredTools.has(mcpBiliToolName("compress")) && !declaredTools.has("compress");
const billingBlockObserved = extractBillingAttributionBlock(systemOf(input.parsed)) !== undefined;
const billingBlockWanted = profile.wantsBillingBlock || billingBlockObserved;
return Object.freeze({
Expand All @@ -255,6 +267,7 @@ export function resolveLaneDecisions(input: LaneDecisionInput): LaneDecisions {
toolsReachable: Object.freeze({ compress: compressReachable }),
compressSurfaceOn,
compressSurfaceOff: !compressSurfaceOn,
mcpDialect,
billingBlockWanted,
});
}
Expand Down
4 changes: 2 additions & 2 deletions src/server/prepare-anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ export async function prepareAnthropic(
rebuiltMessages = [...rebuiltMessages, ...sysNotes.map((text) => ({ role: "user" as const, content: text }))];
}

systemOut = injectSystem(parsed, opts, prompts, loopConfig, surface, visibilityMarkers, laneDecisions.compressSurfaceOff);
systemOut = injectSystem(parsed, opts, prompts, loopConfig, surface, visibilityMarkers, laneDecisions.compressSurfaceOff, laneDecisions.mcpDialect);
// #1637: stamp the steady body's system. NOTE: parsed.system stays the
// #1085 frozen CLIENT head (injectSystem's in-place view) — the round-2
// adapter consumes that frozen head and stamps its own rebuild, so NO
Expand Down Expand Up @@ -539,7 +539,7 @@ export async function prepareAnthropic(
+ countSystemAndToolsTokens(extractSystem(systemOut), toolsOut)
+ imageReserveFor(session, "anthropic", rebuilt, opts, upstreamOrigin);
if (upstreamOrigin) session.stats.lastLocalTextEstimateOrigin = upstreamOrigin;
return { body: JSON.stringify(rebuilt), session, attachedRetrievals, attachedRetrievalNoteIds, processedMessages, originalMessages, anthropicSystem: parsed.system, anthropicBillingBlock, anthropicCacheMarks, anthropicClientCacheControls: clientCacheControls, systemNotes: sysNotes, protocol: "anthropic", stream, compressInjected: injectTools, pluginMode, nudge, nudgeOutcome, prompts, surface, renderTags: renderStrategy, dropReasoning: (msgs: BiliMessage[]) => applyReasoningDrop(msgs, reasoningPlan, log, sessionId) } as Prepared;
return { body: JSON.stringify(rebuilt), session, attachedRetrievals, attachedRetrievalNoteIds, processedMessages, originalMessages, anthropicSystem: parsed.system, anthropicBillingBlock, anthropicCacheMarks, anthropicClientCacheControls: clientCacheControls, systemNotes: sysNotes, protocol: "anthropic", stream, compressInjected: injectTools, pluginMode, mcpDialectNote: laneDecisions.mcpDialect, nudge, nudgeOutcome, prompts, surface, renderTags: renderStrategy, dropReasoning: (msgs: BiliMessage[]) => applyReasoningDrop(msgs, reasoningPlan, log, sessionId) } as Prepared;
}

// #2648: true when any system block pins cache_control.scope:"global". bili's
Expand Down
6 changes: 3 additions & 3 deletions src/server/prepare-google.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { applyCompactionArchive, coveredRealHistoryIds, detectUnannouncedHistory
import { recordConflict } from "../conflict-watch.js";
import { carriesDshLocalCompactionSummary, DSH_LOCAL_COMPACTION_MIN_MISSING } from "./dsh-compaction-guard.js";
import { carriesBiliSnapshotCheckpoint } from "./dsh-authored-compaction.js";
import { ABSORB_TOOL_NAME, READ_ORIGINAL_IMAGE_TOOL_GOOGLE, RULE_TOOL_GOOGLE, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, retrieveToolsFor, withFirstSightDrain, withMarkerIntegrityNote, withSummaryBudgetNote, withProjectAttribution } from "../compress-tool.js";
import { ABSORB_TOOL_NAME, READ_ORIGINAL_IMAGE_TOOL_GOOGLE, RULE_TOOL_GOOGLE, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, retrieveToolsFor, withFirstSightDrain, withMarkerIntegrityNote, withMcpDialectNote, withSummaryBudgetNote, withProjectAttribution } from "../compress-tool.js";
import { absorbToolName, applyAbsorbView, storeEffectiveAbsorb } from "../absorb.js";
import { adoptContentStore, ccrEnabled, ccrLoopConfig, contentStoreOf, imageRescaleToolArmed, retrieveToolName } from "../store.js";
import { rulesEnabled, storeEffectiveRules } from "../rules-feature.js";
Expand Down Expand Up @@ -272,7 +272,7 @@ export async function prepareGoogle(
// constants, so the system anchor stays identical across normal turns
// and round-2 re-requests — skipping them here would fork the prefix
// at every fold and collapse the upstream cache hit.
if (laneDecisions.compressSurfaceOn) sysParts.push(withProjectAttribution(withMarkerIntegrityNote(withSummaryBudgetNote(buildCompressSystemPrompt(prompts, surface?.promptSections), externalSummaryEnabled(config)), visibilityMarkers)));
if (laneDecisions.compressSurfaceOn) sysParts.push(withProjectAttribution(withMcpDialectNote(withMarkerIntegrityNote(withSummaryBudgetNote(buildCompressSystemPrompt(prompts, surface?.promptSections), externalSummaryEnabled(config)), visibilityMarkers), laneDecisions.mcpDialect)));
else if (!isTitleGen && renderStrategy !== "none") {
// #1881: the NEVER-echo prohibition follows the rendered tags, not the tool switch.
const tagsOnly = buildAcpTagsOnlyPrompt("function", prompts, surface?.promptSections);
Expand Down Expand Up @@ -371,7 +371,7 @@ export async function prepareGoogle(
}
snapshotMessages(session, originalMessages);
markDirty(session);
return { body: JSON.stringify(rebuilt), session, processedMessages, originalMessages, protocol: "google", stream, compressInjected: injectTools, pluginMode, nudge, nudgeOutcome, prompts, surface, google: { system: googleClientSystem, model }, systemNotes: sysNotes, renderTags: renderStrategy } as Prepared;
return { body: JSON.stringify(rebuilt), session, processedMessages, originalMessages, protocol: "google", stream, compressInjected: injectTools, pluginMode, mcpDialectNote: laneDecisions.mcpDialect, nudge, nudgeOutcome, prompts, surface, google: { system: googleClientSystem, model }, systemNotes: sysNotes, renderTags: renderStrategy } as Prepared;
}

/** `POST /v1beta/models/<model>:countTokens` — the fold-prune twin of
Expand Down
6 changes: 3 additions & 3 deletions src/server/prepare-openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { compressBreakerArmed } from "../stream.js";
import { applyCompactionArchive, coveredRealHistoryIds, detectUnannouncedHistoryRewrite, foldCoverage, markCompactionBoundary, markDirty, markNativeCompactionBoundary, reconcileNativeCompactionBoundary, REWRITE_MIN_INCOMING_TOTAL, snapshotMessages, type PendingRetrieval, type Session } from "../session.js";
import { carriesDshLocalCompactionSummary, DSH_LOCAL_COMPACTION_MIN_MISSING } from "./dsh-compaction-guard.js";
import { carriesBiliSnapshotCheckpoint } from "./dsh-authored-compaction.js";
import { ABSORB_TOOL_NAME, READ_ORIGINAL_IMAGE_TOOL_OPENAI, RULE_TOOL_OPENAI, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, retrieveToolsFor, withFirstSightDrain, withMarkerIntegrityNote, withSummaryBudgetNote, withProjectAttribution } from "../compress-tool.js";
import { ABSORB_TOOL_NAME, READ_ORIGINAL_IMAGE_TOOL_OPENAI, RULE_TOOL_OPENAI, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, retrieveToolsFor, withFirstSightDrain, withMarkerIntegrityNote, withMcpDialectNote, withSummaryBudgetNote, withProjectAttribution } from "../compress-tool.js";
import { absorbToolName, applyAbsorbView, storeEffectiveAbsorb } from "../absorb.js";
import { adoptContentStore, ccrEnabled, ccrLoopConfig, contentStoreOf, dropRetrievals, imageRescaleToolArmed, pruneExpiredRetrievals, reconcileReloadedRetrievals, renderRetrievalNotes, retrieveToolName, snapshotPendingRetrievals, snapshotRetrievalNotes } from "../store.js";
import { rulesEnabled, storeEffectiveRules } from "../rules-feature.js";
Expand Down Expand Up @@ -311,7 +311,7 @@ export async function prepareOpenai(
// would invalidate the cache every turn.
const sysParts: string[] = [];
if (openaiSystemText) sysParts.push(openaiSystemText);
if (laneDecisions.compressSurfaceOn) sysParts.push(withProjectAttribution(withMarkerIntegrityNote(withSummaryBudgetNote(buildCompressSystemPrompt(prompts, surface?.promptSections), externalSummaryEnabled(config)), visibilityMarkers)));
if (laneDecisions.compressSurfaceOn) sysParts.push(withProjectAttribution(withMcpDialectNote(withMarkerIntegrityNote(withSummaryBudgetNote(buildCompressSystemPrompt(prompts, surface?.promptSections), externalSummaryEnabled(config)), visibilityMarkers), laneDecisions.mcpDialect)));
else if (!isTitleGen && !knobRenderNone()) {
// #1881: the NEVER-echo prohibition follows the rendered tags, not the tool switch.
const tagsOnly = buildAcpTagsOnlyPrompt("function", prompts, surface?.promptSections);
Expand Down Expand Up @@ -476,7 +476,7 @@ export async function prepareOpenai(
}
snapshotMessages(session, originalMessages);
markDirty(session);
return { body: JSON.stringify(rebuilt), session, attachedRetrievals, attachedRetrievalNoteIds, processedMessages, originalMessages, protocol: "openai", stream, compressInjected: injectTools, pluginMode, nudge, nudgeOutcome, prompts, surface, openaiSystemText, systemNotes: sysNotes, renderTags: renderStrategy, dropReasoning: (msgs: BiliMessage[]) => applyReasoningDrop(msgs, reasoningPlan, log, sessionId) } as Prepared;
return { body: JSON.stringify(rebuilt), session, attachedRetrievals, attachedRetrievalNoteIds, processedMessages, originalMessages, protocol: "openai", stream, compressInjected: injectTools, pluginMode, mcpDialectNote: laneDecisions.mcpDialect, nudge, nudgeOutcome, prompts, surface, openaiSystemText, systemNotes: sysNotes, renderTags: renderStrategy, dropReasoning: (msgs: BiliMessage[]) => applyReasoningDrop(msgs, reasoningPlan, log, sessionId) } as Prepared;
}

/** Append the ephemeral nudge to a Gemini `contents` array. Gemini is
Expand Down
Loading
Loading