Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
99422b1
release v0.1.216
github-actions[bot] Nov 16, 2026
a3f0b41
fix(loop): pass the drain flag at the final #5192 drain-drop site (PR…
ranxianglei Nov 16, 2026
1869f0e
fix(cache-ledger): a nudge arm pairs only with nudge-attributed folds…
ranxianglei Nov 16, 2026
28f11a0
fix(gate): agentsR example default, fresh rc files, README knob parit…
ranxianglei Nov 16, 2026
8ed56be
docs(architecture): add src/responses-system-sections.ts to the modul…
Nov 16, 2026
1a4450b
Merge remote-tracking branch 'upstream/master' into HEAD
Nov 16, 2026
1ae8926
fix(storage): persist the turn-final reply at turn end — it only land…
Nov 16, 2026
07bf7e8
Merge branch 'refs/heads/gh-ci-fixes' into pr-6953
Nov 16, 2026
c0242dc
fix(wire): write-back ids use the canonical codec seed — tool calls j…
ranxianglei Nov 16, 2026
b5de5cd
refactor(host): keep the write-back id helper out of kernel/ (kernel-…
ranxianglei Nov 16, 2026
245ecb1
fix(test): recalibrate #2929 probe anchor to nudge positions {3,5,11,14}
Nov 16, 2026
64b0700
test(#2929): probe scans the pre-fold window instead of pinning one u…
ranxianglei Nov 16, 2026
4453de8
fix(store): write-back rows join the client re-send by identity — res…
ranxianglei Nov 16, 2026
75308a0
Merge origin/master into release v0.1.216 (#6922 + #6151, per owner)
ranxianglei Nov 16, 2026
523fc22
Merge PR #6953 into release v0.1.216 (turn-final reply writeback, #6947)
ranxianglei Nov 16, 2026
b93aa5e
Merge remote-tracking branch 'origin/ci-fixes' into sweep-6953
Nov 16, 2026
7247410
test(#2929): make fold probe schedule-independent + hermetic wire shape
Nov 16, 2026
c0fb8d1
Merge remote-tracking branch 'origin/ci-fixes' into 2026-11-16_handof…
Nov 16, 2026
31d76f0
fix(storage): separate reply persistence from the session identity le…
ranxianglei Nov 17, 2026
e8d2577
Merge PR #6953 (direction-C fix) into release v0.1.216
ranxianglei Nov 17, 2026
80daffc
fix(storage): keep the reply stash out of the messages table (directi…
ranxianglei Nov 17, 2026
34b0fc8
Merge PR #6953 direction C1 (reply stash out of the messages table)
ranxianglei Nov 17, 2026
d371092
fix(storage): repair the mysql lane's two latent ingest breakages (PR…
Nov 17, 2026
59e6c86
fix(web): close the two malformed circles in the session-report SVG r…
Nov 17, 2026
5d852d2
fix(lane): read Claude Code's deferred-tools list so the nudge names …
ranxianglei Nov 17, 2026
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
2 changes: 1 addition & 1 deletion .agents/plugins/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"plugins": [
{
"name": "billion-context",
"version": "0.1.215",
"version": "0.1.216",
"source": {
"source": "local",
"path": "./plugins/codex"
Expand Down
2 changes: 1 addition & 1 deletion .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"name": "billion-context",
"source": "./",
"description": "Context-compression plugin for Claude Code · month-long single sessions (billions of tokens) · high compression quality even in small context windows (100K is enough) · 5× fewer tokens",
"version": "0.1.215",
"version": "0.1.216",
"author": {
"name": "ranxianglei"
},
Expand Down
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "billion-context",
"version": "0.1.215",
"version": "0.1.216",
"description": "Context-compression plugin for Claude Code · month-long single sessions (billions of tokens) · high compression quality even in small context windows (100K is enough) · 5× fewer tokens",
"author": {
"name": "ranxianglei"
Expand Down
4 changes: 2 additions & 2 deletions 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.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "billion-context",
"version": "0.1.215",
"version": "0.1.216",
"description": "A context-compression plugin \u2014 small context windows (a 100K context is enough), 5x fewer tokens, month-long single sessions (billions of tokens), and compression quality \u2014 for all agents: pi, OpenCode, Codex, Claude Code, and more. billion-context is all you need.",
"type": "module",
"main": "dist/index.js",
Expand Down
2 changes: 1 addition & 1 deletion plugins/codex/.codex-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "billion-context",
"version": "0.1.215",
"version": "0.1.216",
"description": "Context-compression plugin for Codex — small context windows (100K is enough), 5x fewer tokens, month-long single sessions (billions of tokens), and high compression quality.",
"author": {
"name": "ranxianglei"
Expand Down
3 changes: 2 additions & 1 deletion reference/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ billion-context/
│ │ ├── context-window.ts # Context-window resolution (launcher model channel, beta headers)
│ │ ├── dsh-compaction-guard.ts # Rejects dsh whole-prefix compaction replays (#1729)
│ │ ├── handle.ts # Proxy request pipeline (route triage, compat relay, compress orchestration) (#1440 P2 cut 3)
│ │ ├── handoff-response.ts # Retains parsed assistant output for handoff export without changing request snapshots
│ │ ├── handoff-response.ts # Retains parsed assistant output for handoff export without changing request snapshots; turn-final reply stashed in metadata.handoffReply for durable DB persistence (never lastMessages/messages table — the view is the ref-ledger's territory, #6947)
│ │ ├── headers.ts # Client-provided id sanitization for dump filenames (#286)
│ │ ├── inject.ts # Per-wire tool-injection wrappers + FORCE_TEXT_PROTOCOL switch (#1440)
│ │ ├── observability.ts # Body dumps (dumps/req-*.json, raw/*), unrecognized-path stats
Expand Down Expand Up @@ -304,6 +304,7 @@ billion-context/
│ ├── remote-notices.ts # Remote announcement feed watcher: fail-open polling, last-known-good snapshot (#5548)
│ ├── request-membership.ts # Settle-side membership probe: is this usage report ours (#4805)
│ ├── resolver-wedge.ts # Persistent local DNS resolver wedge detector + alarm (#5221)
│ ├── responses-system-sections.ts # Single source of truth for the Responses-wire developer-section join: steady prepare + round-2 rebuild share one separator (#6922)
│ ├── responses-tool-output.ts # Responses tool-output image parts: projection + patch helpers
│ ├── rollout.ts # Feature rollout: per-install uuid, basis-point buckets, nested cohorts (#3062)
│ ├── runaway-guard.ts # Intrinsic stream terminator for runaway tag/codepoint enumeration (#2346)
Expand Down
15 changes: 12 additions & 3 deletions scripts/gate/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,13 @@ the in-container lane registry), `turnTimeoutMs`, `agents` (Lane P set),
`snapBase` (P/R lanes only: run the candidate's snapBase egress plane ON in the
gate's bili.json — `"all"` = every protocol cohort, `"openai,responses,anthropic,google"`
subset = explicit cohorts, absent/`"off"` = off, byte-identical gate; for
candidate-branch verification, e.g. #6785), `r.{corpusTokens,window,capRatio,
candidate-branch verification, e.g. #6785), `laneScript` (P lanes only: force a
specific harness-script copy, e.g. the bundled `/gate-tools/plugin-lanes.mjs` —
needed when the candidate checkout predates a harness fix; default is the
candidate's OWN `scripts/gate/plugin-lanes.mjs`, bundled copy as fallback),
`snapshotRender` (`"1"` writes `rollout.features.snapshotRender=true` into the
P/R lane bili.json — config tier, beats the 0% rollout default; plugin-mode
lanes stay client-authoritative by design), `r.{corpusTokens,window,capRatio,
cacheRatio}`, `network` (`host` | `bridge`; bridge is the Docker-Desktop
shape — point the config URLs at `host.docker.internal`), `outDir`, `keep`.

Expand Down Expand Up @@ -185,8 +191,11 @@ Two known facts:
turn dies on a ValidationError. The whole lane drops out of the gate; it
auto-promotes when the client ships the protocol — no script change needed.

Not in the default GATE_AGENTS set; runs only when explicitly listed:
`GATE_AGENTS=dsh,dsh-responses,dsh-anthropic,dsh-google,dsh-proxy`.
Not in the default GATE_AGENTS set — runs only when explicitly listed (e.g.
`GATE_AGENTS=dsh,dsh-responses,dsh-anthropic,dsh-proxy`): `dsh-responses`,
`dsh-anthropic`, `dsh-proxy`. `dsh-google` IS in the default set — it degrades
to CLIENT-BLOCKED and is excluded from the tally when the client can't express
the protocol, so listing it there costs nothing.

## Lane flow

Expand Down
4 changes: 2 additions & 2 deletions scripts/gate/README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ scripts/gate/bili-gate.sh --config ... --dry-run # 只打印 docker
model,apiKey}`、`model2.{baseUrl,model,apiKey}`(Lane B)、`rev`、`skip`、
`sourceRepo`、`mirror`(容器 clone 的本地裸 git 镜像——容器零出站,且可走宿主
git 代理)、`gitProxy`、`npmRegistry`(构建依赖镜像;与容器内车道 registry
无关)、`turnTimeoutMs`、`agents`(Lane P 集合)、`agentsR`(Lane R 集合,默认 `dsh,pi`;加 `claude` 跑 anthropic wire 车道)、`snapBase`(仅 P/R 车道:在 gate 的 bili.json 里打开候选的 snapBase 出站平面——`"all"` = 全部协议 cohort,`"openai,responses,anthropic,google"` 子集 = 指定 cohort,缺省/`"off"` = 关,gate 行为逐字节不变;用于候选分支验证,如 #6785)、`r.{corpusTokens,window,capRatio,cacheRatio}`、`network`
无关)、`turnTimeoutMs`、`agents`(Lane P 集合)、`agentsR`(Lane R 集合,默认 `dsh,pi`;加 `claude` 跑 anthropic wire 车道)、`snapBase`(仅 P/R 车道:在 gate 的 bili.json 里打开候选的 snapBase 出站平面——`"all"` = 全部协议 cohort,`"openai,responses,anthropic,google"` 子集 = 指定 cohort,缺省/`"off"` = 关,gate 行为逐字节不变;用于候选分支验证,如 #6785)、`laneScript`(仅 P 车道:强制指定 harness 脚本副本,如内置 `/gate-tools/plugin-lanes.mjs`——候选 checkout 早于 harness 修复时需要;默认优先用候选自己的 `scripts/gate/plugin-lanes.mjs`,内置副本兜底)、`snapshotRender`(填 `"1"` 在 P/R 车道 bili.json 写 `rollout.features.snapshotRender=true`——配置层,压过 0% rollout 默认;插件模式车道按设计仍由客户端权威)、`r.{corpusTokens,window,capRatio,cacheRatio}`、`network`
(`host` | `bridge`;bridge 是 Docker Desktop 形态——把配置里的 URL 指向
`host.docker.internal`)、`outDir`、`keep`。

Expand Down Expand Up @@ -150,7 +150,7 @@ google=`contents`),防止静默换线假绿;首个出站请求存
+ 每回合死于 ValidationError。整条车道不计入 gate,客户端放出该协议后
自动转正,脚本不用改。

不进默认 GATE_AGENTS 集,显式加入才跑:`GATE_AGENTS=dsh,dsh-responses,dsh-anthropic,dsh-google,dsh-proxy`。
其中 `dsh-responses`、`dsh-anthropic`、`dsh-proxy` 不进默认 GATE_AGENTS 集,显式加入才跑(如 `GATE_AGENTS=dsh,dsh-responses,dsh-anthropic,dsh-proxy`);`dsh-google` 在默认集内——客户端表达不了该协议时自动降级 CLIENT-BLOCKED 且不计入统计,所以默认列上它没有代价。

## 车道流程

Expand Down
2 changes: 1 addition & 1 deletion scripts/gate/config.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"turnTimeoutMs": 300000,
"agents": ["dsh", "pi", "codex", "opencode", "claude", "dsh-google"],
"_doc_agentsR": "restart-lane agents, comma list or array. Default dsh,pi; use dsh,pi,claude to also run the anthropic-wire restart lane (prefix topology, harness-managed proxy).",
"agentsR": "",
"agentsR": "dsh,pi",
"_doc_snapBase": "P/R lanes only: run the candidate's snapBase egress plane (storage.snapBase) ON in the gate's bili.json. \"all\" = every protocol cohort; \"openai,responses,anthropic,google\" subset = explicit cohorts; absent or \"off\" = off (byte-identical gate). For candidate-branch verification (e.g. #6785).",
"snapBase": "",
"_doc_laneScript": "Optional: force the P-lane harness script copy, e.g. \"/gate-tools/plugin-lanes.mjs\". Needed when the candidate checkout predates a harness fix (the gate otherwise prefers the candidate's OWN scripts/gate/plugin-lanes.mjs).",
Expand Down
4 changes: 4 additions & 0 deletions scripts/gate/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,10 @@ RC_GATE=${PIPESTATUS[0]}
log "5.5 plugin + 5.7 restart lanes (concurrent)"
CONCURRENT=${GATE_CONCURRENT:-1}
P_PID=""; R_PID=""
# Fresh per-run rc files: a stale copy left in a persistent outDir by an
# earlier run must never be read back if the subshell dies before its final
# echo (that failure direction HIDES a red in release verification).
rm -f "$WORK/.rc-plugins" "$WORK/.rc-restart"
if echo ",${SKIP}," | grep -q ",p,"; then
sub "GATE_SKIP contains p — plugin lanes skipped"
RC_PLUGINS=0
Expand Down
5 changes: 5 additions & 0 deletions src/cache-ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2422,6 +2422,11 @@ export function buildSessionCacheReport(session: Session): BiliCacheReport {
for (let j = i + 1; j < recEvents.length; j++) {
const f = recEvents[j];
if (f.kind === "n") break;
// A model-active fold (mode "a") is NOT the answer to a nudge
// arm — pairing is nudge-attributed by design (#6729), else the
// "not folded" ratchet flag is silently lost when the model
// happens to self-compress after a nudge.
if (f.mode !== "n") continue;
if (paired.has(j)) continue;
paired.add(j);
recEvents[i].paired = true;
Expand Down
2 changes: 1 addition & 1 deletion src/loop/tag-echo-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1680,7 +1680,7 @@ export function createTagEchoFilter(onDrop?: (snippet: string, duringDrain?: boo
// modes agree at true EOF.
const cut = TRUNC_REF_CLOSE.exec(result);
if (cut !== null) {
drop(result.slice(cut.index));
drop(result.slice(cut.index), true);
result = result.slice(0, cut.index);
}
// #4164: EOF resolves any still-held settle as prose — no tag ever
Expand Down
130 changes: 128 additions & 2 deletions src/server/handoff-response.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,82 @@
import type { CoreMessage } from "acp-kernel";
import { anthropicToCore, googleToCore, openaiToCore, responsesToCore } from "acp-kernel/wire";
import type { BiliMessage } from "acp-kernel/wire";
import { anthropicToCore, canonicalToolArgs, ClusterCounter, deriveCanonicalMessageId, googleToCore, openaiToCore, responsesToCore } from "acp-kernel/wire";
import { markDirty, type Session } from "../session.js";
import { log as loggerLog } from "../logger.js";
import { planStoredMessageRow, type HandoffReplyStashRow } from "../storage/ingest.js";

export const HANDOFF_REPLY_MAX_BYTES = 1_500_000;

export type HandoffReply = ReturnType<typeof createHandoffReply>;

export function createHandoffReply(session: Session, canSave: () => boolean = () => true) {
/**
* #6947: canonical base id (WITHOUT the ClusterCounter `_N` suffix) re-derived
* from a core message's OWN fields — the inverse of what each protocol codec
* feeds deriveCanonicalMessageId (#3642). Lets the write-back pre-seed a
* ClusterCounter from the cores already stored, so appended reply ids number
* exactly as the next full codec pass over [stored…, reply…] would (the
* re-send then joins by (msg_id, identity) onto the SAME rows instead of
* retiring + re-ingesting). Host-side on purpose: the kernel boundary (#2092)
* is human-gated and the kernel already exports both seed helpers.
*
* Returns null when the base cannot be derived from core fields alone: image
* parts (the #3751 payload fingerprint lives in sidecars the handoff capture
* never sets — unreachable here, null is the honest answer) and unknown
* content types. Callers skip nulls: an under-count can only shift a cluster
* SUFFIX for an identical repeated identity, never mint a wrong bare id.
*/
function baseIdOfCore(m: BiliMessage): string | null {
const text = m.text ?? "";
switch (m.contentType) {
case "text":
if (m.imagePart) return null;
return deriveCanonicalMessageId(m.originalRole ?? m.role, "text", text);
case "reasoning":
return deriveCanonicalMessageId("assistant", "reasoning", text);
case "tool-call":
return deriveCanonicalMessageId("assistant", "tool-call", canonicalToolArgs(text), { toolName: m.toolName });
case "tool-result":
return deriveCanonicalMessageId("tool", "tool-result", text, { toolName: m.toolName });
default:
return null;
}
}

/**
* #6947 join polish: re-stamp the sidecars each protocol codec would add on
* the NEXT re-send, so the write-back row's stored bytes join the re-send
* row's by identity (identityOfStoredContent strips only id/wireIndex —
* every other field counts). Without this, the re-send ingest lands a
* second row for the same logical message (tombstone churn + the content
* CAS storing the reply bytes twice) on long sessions:
* - openai reasoning cores carry `reasoningContent` (the codec stamps the
* reasoning text a second time — kernel/src/wire/openai.ts);
* - openai clients (pi) re-serialize tool-call args with parse +
* JSON.stringify (compact, key order preserved) and the anthropic codec
* stores safeStringify(input) — both reduce to the same normalization
* of the verbatim streamed args.
* Lanes whose codecs attach payload sidecars the text capture cannot
* reproduce (google rawGoogleParts / responses rawResponsesItem /
* anthropic thinkingSignature) keep the write-back row byte-distinct —
* accepted residual, same class as client round-trip drift.
*/
function restampForJoin(protocol: string | undefined, m: CoreMessage): CoreMessage {
const b = m as BiliMessage;
const text = b.text ?? "";
if (b.contentType === "reasoning" && protocol === "openai") {
const stamped: BiliMessage = { ...b, reasoningContent: text };
return stamped as CoreMessage;
}
if (b.contentType === "tool-call" && (protocol === "openai" || protocol === "anthropic")) {
try {
const parsed: unknown = JSON.parse(text);
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return { ...m, text: JSON.stringify(parsed) };
} catch { /* non-JSON args: keep the verbatim bytes */ }
}
return m;
}

export function createHandoffReply(session: Session, canSave: () => boolean = () => true, protocol?: string) {
const request = session.stats.requests;
const snapshot = session.lastMessages;
const messages = new Map<string, { message: CoreMessage; bytes: number; textBytes: number; lastCodeUnit: number }>();
Expand Down Expand Up @@ -48,6 +117,62 @@ export function createHandoffReply(session: Session, canSave: () => boolean = ()
discard,
save() {
if (discarded || !messages.size || session.stats.requests !== request || session.lastMessages !== snapshot || !canSave()) return;
// #6947 turn-final write-back (direction C — persistence is
// separated from the session identity ledger): the reply rows
// historically only persisted when a LATER request re-sent them
// (snapshotMessages replaces lastMessages from the request
// array), so an idle session's last turn never reached the store
// — the web UI kept showing the previous (stale) reply forever.
// We must NOT append the reply to the snapshot: lastMessages is
// the single source of truth for the resident window (digest
// parity, web view, fork refs), and the reply's REF is minted by
// the kernel only when a request presents it — pushing it here
// created a window where fork/snapshot saw a message with no
// ref and 409'd (review regression, #6953).
// Instead the captured reply is stashed as plan-ready rows in
// metadata.handoffReply (persisted → both views digest-equal).
// Ids are derived EXACTLY as the next codec pass will derive
// them: the SAME canonical seed the codecs feed
// deriveCanonicalMessageId (#3642 — role|contentType with the
// toolCallId slot pinned empty, toolName, and canonicalToolArgs
// for tool calls; wire toolCallIds are transport plumbing, never
// content identity) and the same cluster numbering (Nth
// occurrence of the same base, counted in arrival order over the
// snapshot). The planners turn the stash into trailing
// NON-TAIL log rows (never tailSeqs), and the re-send — full or
// delta path — JOINs them in place by msg_id+identity (#4390)
// on EVERY content type, so the #3133 fast path stays green.
// Worst case (client round-trip drift): one refused delta + one
// redundant full re-ingest — never wrong rows.
// Skipped when the snapshot is a bounded folded re-render: its
// array is a pruned view, not the raw tail the store appends to.
if (session.lastMessagesFolded !== true && Array.isArray(snapshot)) {
const clusters = new ClusterCounter();
for (const m of snapshot) {
const b = baseIdOfCore(m);
if (b !== null) clusters.next(b);
}
const rows: HandoffReplyStashRow[] = [];
for (const entry of messages.values()) {
const m = restampForJoin(protocol, entry.message);
const b = baseIdOfCore(m);
// b is null only for image-part cores (the #3751 payload
// fingerprint lives in sidecars the capture never sets —
// it has no imagePart). Skip the row in that unreachable
// case: without a content-derived id the row could never
// join the re-send and would only ever be a duplicate —
// the reply then persists on re-send, as pre-#6947.
if (b === null) continue;
rows.push(planStoredMessageRow({ ...m, id: clusters.next(b) }));
}
// Each turn's save() overwrites the stash; after the re-send
// presents the reply as a view row the planner gates it out
// by msgId — no explicit consumption needed. The row bytes
// duplicate metadata.handoffResponse for one turn (both
// bounded by the HANDOFF_REPLY_MAX_BYTES cap) — accepted to
// close the idle-persistence gap without touching the view.
if (rows.length > 0) session.metadata["handoffReply"] = { request, rows };
}
session.metadata.handoffResponse = { request, messages: [...messages.values()].map((entry) => entry.message) };
markDirty(session);
},
Expand Down Expand Up @@ -76,3 +201,4 @@ export function captureHandoffJson(reply: HandoffReply | undefined, protocol: st
reply.discard();
}
}

Loading
Loading