Hermes defaults tools.tool_search to "auto": model_tools.py:517-534 rewrites the
plugin toolset into the tool_search/describe/call bridge, so the outgoing request
never carries compress/decompress/acp_status. _plugin_tools_visible() therefore
returns False and on_llm_request bailed out entirely — dropping x-bili-plugin,
x-bili-plugin-conversation, the model and the context-window headers. The proxy
then minted a pfa-* anonymous session (session.ts:1330): /acp's status lookup
404'd and read as "No model request yet", and the window fell back to 200K.
Decouple identity/budget from whoever executes compression. The proxy advertises
x-bili-plugin-compression in the manifest headers; the plugin stamps "proxy" only
when that capability is advertised AND the ACP tools are absent from the request,
and the proxy honors it only alongside the x-bili-plugin marker (same degradation
shape as #2155's plugin-channel death and #2268's pi-subagent role whitelist).
Identity and budget now bind to the conversation; the proxy keeps owning the
compress injection while the tools stay deferred.
Tests: plugin-protocol gains a 4-leg case (deferred/subset/no-override/no-marker —
the last one must still 404) and hermes-native a defer-fallback driver scenario.
Union of intent for the single conflict (src/agent/dsh-native.ts):
keep #3501's explicit BILLION_CONTEXT_ATTACH priority in the pinned-origin
probe AND master's #3616 superseded-flight guard after the await.
Aligns the newest injected tool with the acp_ prefix convention used by
every bili tool added after the original three (acp_status/acp_cache/
acp_retrieve) so models and users recognize bili-injected tools at a
glance. The feature is unreleased (still in the [Unreleased] batch), so
the rename carries zero user-facing compatibility surface — no legacy
name support added.
Touches: READ_ORIGINAL_IMAGE_TOOL_NAME constant (all four wire shapes and
every registration/dispatch site reuse it), model-visible annotation and
error text in image-rescale.ts, comments, CONFIGURATION.md en/zh, the
CHANGELOG [Unreleased] entry, test assertions (sorted tool-name lists
re-sorted for the new position), and the wire-contract goldens
regenerated via scripts/update-wire-contract-goldens.ts — only
manifest-default.json and manifest-optin.json changed (kernel.json never
pinned this host-side tool).
Restore the absorb machinery reverted by #3309, as the base for the
media-scoped revival (#3398): conflicts resolved keeping both the restored
absorb wiring and post-#3309 additions (withProjectAttribution #3298,
withAcpNotes #3252). src/proxy-tool.ts is deleted again — its only export
isProxyToolFor moves back to absorb.ts (absorb-aware, pre-#3309 shape).
This revert is intentionally NOT pushed alone; the media-only scope
restriction lands on top in the same PR.
The `absorb` tool let a model distill oversized tool results through an injected
tool, but its prompt activation was gated on `shouldInject` alone while tool
injection was additionally gated on `!pluginMode`. In every plugin-mode lane
(pi/omp/opencode/dsh) with compress.absorb.enabled=true the model was therefore
told to call a tool that never appears on the wire — unknown-tool spin, same
symptom family as #3177 (which fixed the compress surface). Owner decision:
remove the feature entirely rather than gate it.
- delete src/absorb.ts; relocate isProxyToolFor to src/proxy-tool.ts (absorb branch dropped)
- drop absorb from config schema/validation/divergence-warn, compress-settings,
the four prepare-* wire paths, relay, preflight, side-request, stream*, loop/core,
plugin manifest, server inject; drop ABSORB_TOOL* from compress-tool + opencode-v2
- delete tests/absorb.test.ts + tests/absorb-plugin.test.ts; strip absorb
fixtures/assertions/golden-specs from affected suites
- regenerate wire-contract goldens (bili.json, manifest-optin.json); kernel.json unchanged
- docs en/zh: remove absorb config sections and cross-references
The low-level m00885 emission-drop machinery (adapter absorbArmed params,
tag-echo-filter tcHold path) is kept dormant/unarmable: no request can arm it
after this removal. Kernel is untouched (human-gated).
Closes#3293
Test harnesses awaited server 'close' after only calling close(), leaving teardown completion to the client-side keep-alive timeout (~4s undici pool). In that window the event loop can drain and node:test cancels every pending test in the file ('Promise resolution is still pending but the event loop has already resolved', cancelledByParent cascade) — reproducible 3x on windows-22 for tests/plugin-fork.test.ts via PR #3166 CI.
Fix: call closeIdleConnections() on proxy and upstream right after close() in every paired teardown (138 test files, ~400 sites), so the close event fires immediately. Tests-only; no product code touched.
Closes#1970
- package.json: npm run typecheck now targets the root tsconfig.json
(include: src + tests) instead of tsconfig.build.json (src only);
all four CI workflows inherit the widened gate via the script.
- tsconfig.json: lib ES2022 -> ES2024 (type-only; tests use
Promise.withResolvers & co.; src stays clean under it; no effect on
tsup/esbuild output).
- 276 test files: type-level-only fixes (import sources, missing
fixture fields filled with src-default values, narrowing, explicit
annotations, single-expression casts). No assertion changes, no
runtime behavior changes.
- src/agent/dsh-acp.ts: export CommandOutcome / CommandsService types
(type-only; erased at build).
- remove every model-visible conversation id: the wire system note
(withConversationIdNote), MCP manifest conversation_id params (#760),
search_context cross-conversation description (#841)
- new src/tool-ring.ts: per-session ring of
sha256(name + NUL + stableStringify(args minus conversation_id)) over
outbound tool_use; capacity 32, TTL 10min, hash-index evicted in sync
- record witnesses on all five plugin response lanes (openai/anthropic/
google chat SSE, responses SSE, non-stream JSON) — observe-only, bytes
still forwarded verbatim (#1039)
- handlePluginTool routing ladder: unique witness wins (even over a
differing body id — claude-code subagent correctness); collision with
no id -> loud 400 refuse-to-guess; no witness -> body id path; neither
-> single-active arbitration inside the TTL window, else loud 400
- mcp shim no longer hard-fails id-less tool calls: forwards them for
proxy-side routing; per-call override + legacy strip kept for compat
- wire-contract goldens regenerated (conversation_id param gone)
- README zh/en kimi lane notes updated
Fixes#1685Fixes#1611
stripKernelSummaries keyed suppression on an inbound tool-call matching
block.compressCallId, which is unsatisfiable for folds executed through
POST /__bili/plugin/tool: they mint a synthetic plugin_<ts> id the client
can never echo back, even though the client's own re-sent compress pair
rides inbound history every turn and IS the summary carrier by contract.
Result: the kernel's in-place [Compressed conversation section] anchor rode
every post-fold body alongside the pair — one extra full copy of every
active summary per turn, contradicting README 'Two compression modes'.
Strip on the plugin_ callId prefix instead of (not in addition to) the
echo match: the prefix is minted at exactly one site, so it marks precisely
the blocks whose client necessarily holds its own pair. Preflight blocks
(no compressCallId) keep skipping — no tool call exists for them, so their
in-place anchor remains the only carrier (#247). Proxy/wire-loop blocks
keep the existing id-match logic unchanged.
Regression test: the plugin tool-API fold test now asserts the post-fold
body carries no '[Compressed conversation section] — <topic>' anchor while
the client's orphaned pair stays visible (KEEP_LAST_ORPHANED=2).
Owner decision on #1402: the #1399 'model has full rights over session
rules' ruling covers the CAPABILITY (record/list/delete/clear, unprompted
use allowed) within sessions where the feature is enabled — it does not
inject the tool for everyone. Revert rulesEnabled/effectiveRulesEnabled
to explicit-enable (=== true), flip every default-on assertion back
(rules/manifest/mcp-shell/wire-contract/codex-official), regenerate the
default golden manifest without acp_rule, and update README/CONFIGURATION
(en+zh) + PLUGIN.md wording.
诉求 1 — compress.rules defaults ON (owner decision: the model owns session rules):
- rulesEnabled(): absent block now means enabled; only explicit false disables
- new effectiveRulesEnabled() for the session-level plugin-tool paths
(loop/core executeProxyTool, absorb isProxyToolFor, plugin tool allowlist)
- kernel needs no change: acp_rule is unconditionally protected there
诉求 2 — human-side parity: pi/omp /acp-rule now forwards the full op set:
- bare = list, text = record (unchanged)
- 'remove <id>' -> { delete: id }; bare 'remove' warns with usage, no forward
- bare 'clear' -> { clear: true }; 'clear <text>' records (typo guard)
Docs en+zh: rules default line + migration note, /acp-rule usage incl.
remove/clear, stale '#1178' claim removed. Tests: default-on expectations
flipped at every gate site, new forwarding/regression cases, wire-contract
ledger + manifest-default golden regenerated via scripts/update-wire-contract-goldens.ts.
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).