The /__bili/plugin/manifest route read absorbEnabled(config)/rulesEnabled(config) off the raw kernel-default config (opts.kernelConfig), while the per-request path resolves opts.compress onto it via applyCompressSettings. A user enabling compress.absorb.enabled in their config file therefore got [ACP absorb] prompts on the wire but no callable absorb tool registered by hosts that register only manifest tools (Pi native plugin) — the prompts could never be executed.
Resolve the global compress settings at the manifest route so both paths agree; per-session/provider enablement stays execution-time-gated. Adds enabled + disabled regression tests exercising the real file-config path.
Fixes#1278
Issue #800: prove with data that compression does not wreck the prompt
cache. Every provider usage report is decomposed into an exact additive
identity — missed = new content + compression re-pay + ttl/other — so the
grand ledger always closes against the provider-reported totals.
- src/cache-ledger.ts: session-scoped ledger in metadata.cacheLedger
(512-line ring + exact aggregates + fold events with measured T/h/k);
folds detected from state.blocks diff (proxy mode eager at
applyRanges, plugin mode lazy at usage time), X via tokenSnapshot
prefix sums; incremental math delegates to acp-kernel decomposeSample
so streaming and batch reports agree bit-for-bit.
- executeProxyTool / executeAnthropicProxyTool dispatch the new read-only
acp_cache tool (kernel-defined) -> formatted report.
- GET /__bili/cache-report?session=<id> management endpoint (JSON).
- recordUsage (proxy mode) and applyUsageSample (plugin mode) feed the
ledger; acp-kernel pinned to the release containing PR
ranxianglei/acp-kernel#297.
Extends the #760/#761 per-call conversation_id plumbing with a second, execution-layer semantic for search_context: when the id does not match the caller's own session (verbatim or canonical alias), the call searches that historical session instead of re-routing to it.
- resolveForeignSessionState: resident memory first (peekSession / findSessionByCanonicalId), else SessionStore.loadStateForSearch — a new strictly read-only persistence path that never schedules saves (unlike loadSync, which has the #408 clamp side effect).
- Cross-session results are scoped and namespaced: output lines carry 'in session <id>' plus a note that block ids are per-session namespaces; decompress stays anchored to the current session, bulk content via 'bili export <id> [--full]'.
- Unknown ids fail loudly ([search_context FAILED: unknown session ...]) without creating state.
- search_context's conversation_id param description is specialized in the plugin manifest (routing text kept for all other tools); wire-mode schemas gain the optional param via BILI_* derived constants so proxy-mode clients can target historical sessions too. Kernel constants are never mutated.
- MCP shim keeps conversation_id in args only for search_context so the proxy resolves the target itself; routing semantics for every other tool are unchanged, and no tool call ever mutates a foreign session.
Closes#841
The existing #656 test exercises the cooperative plugin protocol
(x-bili-plugin-conversation). Add a parallel test that drives the actual
Claude Code identity-binding path (x-claude-code-session-id + persistent
identity register): a stale pre-resume id 404s, status?fallback=latest
resolves the active conversation, and the adopted id then works.
Fixes#656.
Claude Code resumes fork a NEW session id after MCP children are spawned,
so the shim's env-captured CLAUDE_CODE_SESSION_ID goes stale and every tool
call 404s with 'unknown plugin conversation' for the rest of the session
while the proxy keeps serving the conversation under the new id.
- mcp.ts: on that exact 404, adopt the proxy's most-recent active
conversation (status?fallback=latest) and retry once. Identity-bound
hosts only; BILI_MCP_NO_ORPHAN_ADOPT=1 opts out for multi-session setups.
- plugin.ts: status fallback now reports the RESOLVED conversation id
(it used to echo the caller's stale id back, so adoption was impossible).
- plugin.ts: split the tool-endpoint 404 into its two real causes
(never-registered id vs session-not-resident) and log the rejection -
these 404s used to be invisible in bili.log.
- tests: fallback resolution + adopted-id tool call; never-registered
wording assertion.
handlePluginStatus fed buildStatusPanel the prepare-time snapshot
(mem.nudge) remembered at the last model request. A compress executed
through the plugin tool API mutates session.state without re-running
prepare, so between compress and the next request the panel mixed live
blocks with stale, already-consumed ranges (#387).
Recompute the nudge on every panel request via processTurn over the
remembered pre-fold view against the CURRENT session.state; on failure
omit the nudge/ranges sections instead of falling back to the stale
snapshot.
server.ts passes { core, config, log } to handlePluginStatus; callers
in tests updated for the new deps argument. New e2e in
plugin-protocol.test.ts fails pre-fix (panel kept recommending the
just-compressed m00001..m00002 range).
- src/agent/opencode.ts: 1.8KB plugin shipped as dist/agent/opencode.js;
registers the acp command via the config hook, renders the proxy's
buildStatusPanel through an ignored no-reply chat message. Active only
under BILLION_CONTEXT_PROXY (launcher), no-op otherwise.
- prepareOpencodeHttpRewrite(pluginPath?) injects the plugin's absolute
path into the throwaway OPENCODE_CONFIG copy so bili opencode needs no
install step and never touches the real opencode.json.
- handlePluginStatus(..., fallbackLatest): ?fallback=latest resolves an
unknown conversation to the most recently active session (opencode
plugins cannot stamp x-bili-plugin headers); response gains
fallback:true. Unchanged 404 without the param.
- The register-POST path was deliberately dropped: registering suppresses
wire tool injection, and this plugin cannot natively register the 4
tools (opencode tool hook needs zod). Wire injection + fallback status
keeps the model surface intact (verified: round-2 tools list ends with
compress,decompress,search_context,acp_status).
Some relays echo a schema-shaped usage in message_delta where
input_tokens/cache_read_input_tokens are present but 0 (the spec fields
are normally absent — message_start is authoritative, and the input
context is fixed within a turn). Merging the 0 overwrote message_start's
real values in both usage paths:
- loop mode (adapter-anthropic.ts): roundInput/roundCollapsed to 0 →
recordUsage set lastInputTokens to the cached portion only
- plugin mode (plugin.ts usageFromSseEvent): mergeUsageSample zeroed
acc.inputTokens → applyUsageSample collapsed the total to cached-only
The nudge/truncate denominator then under-reported by ~6x (e.g. 11 instead
of 66 in the regression fixture), so compression never fired on
cache-heavy sessions. A 0 can never be a legitimate update to a fixed
in-turn input, so only > 0 values are adopted.
Adds regression tests for both paths (verified to fail without the fix).
lastInputTokens / cache-hit rate were computed as `prompt + cached`
uniformly, which is only correct for Anthropic (where input_tokens is the
NEW portion and cache_read is reported separately). For OpenAI and
Responses the reported input total ALREADY includes the cached subset, so
adding it again double-counted cached tokens:
- lastInputTokens inflated by the cached amount -> the nudge decision
overestimates context size -> premature compression.
- the logged cache-hit % was deflated (cached/(prompt+cached) instead of
cached/prompt); e.g. a true 90% hit read ~47%.
- cumulative inputTokens was protocol-inconsistent (Anthropic new-only vs
OpenAI/Responses total), so the web cacheHitPct could exceed 100%.
Fix: normalize to the true TOTAL context per protocol via a shared
usageTotals() helper (util.ts) and thread the wire protocol into every
usage consumer:
- loop/core.ts recordUsage (streaming compress-loop path)
- server.ts non-streaming usage block
- plugin.ts applyUsageSample (plugin-mode passthrough)
Adapters are unchanged (they still emit protocol-native usage to the
client-facing completion). The only behavior change is the internal stats:
lastInputTokens, cumulative inputTokens, and the hit-rate are now the
protocol-correct total.
tests: add tests/usage-totals.test.ts pinning the per-protocol totals;
update the plugin streaming expectation from 55 (new-only) to 66 (true
total = input 55 + cache_read 11) so cacheHitPct stays a valid ratio.
Resolve conflicts with #161 (plugin protocol) landing on master:
- src/server.ts import: union — keep launcher register symbols
(handlePluginRegister/consumePluginRegisterFor/takePendingPluginRegister),
adopt master's pluginReportedContextWindow; drop pluginContextWindowHeader
(unused after master's rename, still exported as internal helper)
- tests/plugin-protocol.test.ts import: union of both sides' harness symbols
Verified: 453/453 tests pass, npm run typecheck clean.
- launcher.ts buildCodexMcpArgs: args were double-encoded
(JSON.stringify applied twice) so codex received a TOML string where it
expects a sequence — every 'bili codex' with injection died at startup
with: Error loading config.toml: invalid type: string ... expected a
sequence in mcp_servers.bili.args. Now emits args=["<script>"] (a JSON
array literal, which is valid TOML). Verified with codex-cli 0.147.0.
- cli.ts plugin-register: sends identity: true — the documented
'bili plugin-register $CLAUDE_SESSION_ID' usage registers a claude
session id that claude code puts on every model request, so it must
bind by identity match, not consume the next NEW session.
- plugin.ts takePendingPluginRegister: headless registrations now expire
after 10 min (PENDING_REGISTER_TTL_MS). The ts field was recorded but
never used; a stale/orphaned registration could otherwise be bound to
an unrelated later session, turning it into plugin mode with a foreign
conversation id.
- tests: codex -c args assertion now verifies the value is a TOML array
(would have caught the double-encoding); new TTL expiry test.
x-bili-plugin-context-window and x-bili-plugin-conversation were honored
from ANY request, not just plugin requests. A plain client (or any client
on a LAN-exposed deployment) could rewrite the nudge denominator and
steer the proxy's session identity by name alone.
- plugin.ts: pluginReportedContextWindow() only returns the reported
window when x-bili-plugin is present; server.ts uses it in the
native-window cascade.
- session-id.ts: x-bili-plugin-conversation is only consulted when the
marker header is present (the protocol always sends both together);
legacy client headers are unchanged.
- test: header gating unit cases (marker on/off, bad value, legacy
fall-through).
BILLION_CONTEXT_PROXY is exported by the launcher env builders (pi/codex/
claude) so agent-side plugins can detect the proxy in MITM transparent
mode (no /bili/ prefix to sniff). x-bili-plugin-context-window reports
the agent's own model window - the authoritative native source (outranks
table/registry; operator compress.modelContextLimit still wins) - most
valuable for private relays behind MITM. GET /__bili/plugin/status exposes
context-level usage (contextTokens = input+cache-read, the same value
nudges read) for plugin status UIs. Plugin stream passthrough now applies
usage before res.end() so the client's next request always sees it.
PLUGIN.md sections 4-5. Tests 426/426.
Outside half of the inside-outside cooperation (issue #1): an agent-side
plugin registers the 4 ACP tools natively (schemas served by
GET /__bili/plugin/manifest, single source of truth) and sends
x-bili-plugin / x-bili-plugin-conversation headers; the proxy suppresses
wire tool injection for that session, passes responses through verbatim
(with usage sniffing), and executes plugin-forwarded tool calls under the
session lock via POST /__bili/plugin/tool. Session identity becomes the
plugin's real conversation id. Wire mode unchanged (419 tests untouched).
Spec: PLUGIN.md. Tests: tests/plugin-protocol.test.ts (6).