Skip to content
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag

## [Unreleased]

### dsh 归因正面修:llm/stream 会话身份随请求对象(#4082)

- dsh 的 LlmRuntime 在每次派发上盖章 `options.sessionId`(主循环/压缩/标题生成,重试重发也重新盖章),且把 llm/stream waterfall 文档化为官方拦截点。插件现在把每条流的迭代包进以该 sid 为键的 AsyncLocalStorage:适配器的 fetch 读到的会话身份**跟随请求对象,不再依赖异步链形状**——429 重试链、无 initiator 的 agentless 侧调用(compaction/标题)、已销毁的 initiator 作用域、宿主运行时缺口(#2975/#3918/#4082)全部免疫。
- 归因读取顺序:llm/stream sid(先,派发自己的真相)→ `ctx.agents.currentInitiator()`(回退)→ 协商式指纹桥(PR #4094,兜底保留)。压缩侧调用天然带归因,喂 dsh-authored compaction。
- 无 `sessionId` 的 agentless 车道(auto-review)原样透传,现有阶梯决定。
- 一次性可见性:`bili-native-dsh: llm/stream attribution active — session id rides the request object (#4082)`。


- dsh 归因丢失协商回退(#4082/#3918/#2975):宿主重试/切模型/睡眠恢复的请求脱离 agent 执行链,归因为空时此前直接裸发上游(无压缩无护栏,且会话永久失守)。现在 shim 在归因正常时学习「车道 → 会话 + 边界指纹」(该次请求最后一条消息),归因丢失时若请求历史包含某已知边界且唯一命中,则由 takeover 门认领并原子补盖 x-bili-plugin-conversation(#3370 纪律),请求照常走插件车道;fork 从中间分叉不含边界 → 不认,行为与今天逐字节一致;无证据/多义 → 维持直发。每个 2xx 响应新增 x-bili-session 头(协议级,配合客户端可自持身份,见 PLUGIN.md);认领事件进 client 日志可见。
### 压缩

- **压缩区间跨越受保护消息时在边界截断,不再挖洞(#3953)**:此前模型选的区间如果中途扫过受保护消息(最近 N 条/最近一条用户消息),受保护消息会被从覆盖名单里挖掉、两侧照折——其回复(在受保护提问之后的消息)被摘要盖住,而摘要锚点落在提问之前,模型看到"答案摘要排在自己的问题上方"。现在区间在首个受保护消息处截断:从该位置起(受保护消息与其后的回复)全部保持可见,因果序不再被打穿。受保护消息恰在区间尾部的常规擦边(咨询式保护区原本设计的形状)行为逐字节不变;截断会清空区间或会劈开工具调用/结果对的形状退回原挖洞语义(吸收保护的吸收对不受影响)。
Expand Down
2 changes: 2 additions & 0 deletions PLUGIN.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ On **every model request** the plugin sends:

- `x-bili-plugin-agent: main` (optional) — vetoes side-request demotion for this one request. Requests are otherwise demoted to the verbatim side lane when they look like auxiliary traffic (#388: small `max_tokens`, or a known side persona such as opencode's title generator). A full main turn that re-sends the conversation can still trip those heuristics; stamping `main` keeps it on the kernel path so it captures history, stays compressible and remains forkable. Any other value declares the side persona id itself (it is then matched against the known side-request persona set, not treated as `main`).

Every proxied 2xx response carries `x-bili-session: <server-side session id>` (#4082) — the id the proxy itself keys this conversation by. A client that keeps its own conversation object may store it from any response and send it back as `x-bili-plugin-conversation` on later requests (retries, model switches, resends after resume), keeping identity stable even when the request is driven from an execution context the plugin cannot attribute. The dsh bridge does this automatically in-process (it learns the mapping while attribution works and re-stamps when it breaks); other hosts may adopt the header directly.

Effects on the proxy for that session:

- Wire-level tool injection is **suppressed** (tools are native; no duplicates).
Expand Down
238 changes: 238 additions & 0 deletions src/agent/conversation-recall.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
/**
* Negotiated conversation recall (#4082, #3918, #2975).
*
* The native lanes attribute a model request to a host session by reading the
* host's execution context (AsyncLocalStorage initiator). That context is
* MISSING on the paths the host drives outside an agent turn — quota/429
* retries, model switches, and post-resume resends — so those dispatches fall
* out of the takeover gate into raw DIRECT sends: compression off, guards
* off, and (because the host keeps growing the same conversation) the damage
* is permanent for that session (#3918).
*
* This module is the fallback identity: while attribution WORKS, the shim
* learns `lane → (session id, boundary fingerprint)` — the boundary is the
* fingerprint of the LAST message of the attributed request's body. When
* attribution is later missing on the same lane, a dispatch whose history
* CONTAINS a remembered boundary is provably that session's continuation
* (retries and model switches resend the identical history; that is the
* problem AND the proof), and the gate can claim it again with the server's
* own session id.
*
* Safety rules:
* - The boundary must be CONTAINED in the incoming history and the match
* must be UNIQUE across the lane's remembered sessions — otherwise no
* stamp (behavior stays exactly today's direct send). Never guess.
* - A fork that diverges from mid-history does not contain the parent's
* latest boundary → never claimed. Only a fork copied from the very END is
* physically indistinguishable from a continuation; the TTL window plus
* reconcile drift isolation bound that rare² case (and #2399 adoption
* semantics make even it semantically sound).
* - Entries expire (RECALL_TTL_MS) and each lane keeps at most
* RECALL_PER_LANE sessions (LRU) — retries happen within seconds of the
* original dispatch, this is a short-window bridge, not a registry.
*/
import { createHash } from "node:crypto";

const RECALL_TTL_MS = 10 * 60_000;
const RECALL_PER_LANE = 8;
const RECALL_MAX_LANES = 64;

type ConversationRecallStats = {
lanes: number;
sessions: number;
learned: number;
recalled: number;
rejectedNoLane: number;
rejectedNoBoundary: number;
rejectedAmbiguous: number;
expired: number;
};

type LaneEntry = { sid: string; boundaryFp: string; at: number };

const lanes = new Map<string, Map<string, LaneEntry>>();
const stats: ConversationRecallStats = {
lanes: 0,
sessions: 0,
learned: 0,
recalled: 0,
rejectedNoLane: 0,
rejectedNoBoundary: 0,
rejectedAmbiguous: 0,
expired: 0,
};

function sweep(now: number): void {
for (const [laneKey, perLane] of lanes) {
for (const [sid, entry] of perLane) {
if (now - entry.at > RECALL_TTL_MS) {
perLane.delete(sid);
stats.expired++;
}
}
if (perLane.size === 0) lanes.delete(laneKey);
}
while (lanes.size > RECALL_MAX_LANES) {
// Simple bound: drop the least recently updated lane.
let oldestKey: string | undefined;
let oldestAt = Infinity;
for (const [laneKey, perLane] of lanes) {
for (const entry of perLane.values()) {
if (entry.at < oldestAt) {
oldestAt = entry.at;
oldestKey = laneKey;
}
}
}
if (oldestKey === undefined) break;
lanes.delete(oldestKey);
}
stats.lanes = lanes.size;
stats.sessions = [...lanes.values()].reduce((n, perLane) => n + perLane.size, 0);
}

/**
* Lane key: endpoint origin + pathname only. Query strings can carry
* per-request noise, the model field changes on exactly the #3918 switch-
* model retry this must catch, and auth tokens rotate (bearer refresh / key
* swap — an auth-keyed lane would be orphaned on the very retry the bridge
* exists for). The lane is only the SEARCH NAMESPACE; the identity evidence
* is the boundary fingerprint plus its uniqueness across the lane.
*/
export function recallLaneKey(url: string): string {
const u = new URL(url);
return `${u.origin}${u.pathname}`;
}

/** Cheap probe for gate-side short-circuiting: no learned session on this
* lane ⇒ no body parsing or fingerprinting is worth doing at all (agentless
* sidecars hit this path constantly with bodies that can never match). */
export function recallLaneHasEntries(laneKey: string): boolean {
const perLane = lanes.get(laneKey);
return perLane !== undefined && perLane.size > 0;
}

/** Stable fingerprint of one wire message (byte-stable: hosts serialize
* deterministically, and a retry resends the identical serialization). */
function recallFingerprintOfMessage(message: unknown): string | undefined {
if (typeof message !== "object" || message === null) return undefined;
const role = (message as { role?: unknown }).role;
const content = (message as { content?: unknown }).content;
if (typeof role !== "string" || (content !== undefined && typeof content !== "string" && typeof content !== "object")) {
return undefined;
}
try {
return createHash("sha256").update(JSON.stringify({ role, content })).digest("hex").slice(0, 24);
} catch {
return undefined;
}
}

/** Fingerprints of every message in a wire `messages` array. */
export function recallHistoryFingerprints(messages: unknown): Set<string> {
const out = new Set<string>();
if (!Array.isArray(messages)) return out;
for (const m of messages) {
const fp = recallFingerprintOfMessage(m);
if (fp !== undefined) out.add(fp);
}
return out;
}

/** The boundary fingerprint of a body: its LAST message. */
export function recallBoundaryOfMessages(messages: unknown): string | undefined {
if (!Array.isArray(messages) || messages.length === 0) return undefined;
for (let i = messages.length - 1; i >= 0; i--) {
const fp = recallFingerprintOfMessage(messages[i]);
if (fp !== undefined) return fp;
}
return undefined;
}

/** Learn (attribution ok): this session's latest dispatch boundary on this lane. */
export function learnConversation(laneKey: string, sid: string, boundaryFp: string): void {
const now = Date.now();
sweep(now);
let perLane = lanes.get(laneKey);
if (perLane === undefined) {
perLane = new Map();
lanes.set(laneKey, perLane);
}
// LRU touch + TTL refresh.
perLane.delete(sid);
while (perLane.size >= RECALL_PER_LANE) {
let oldestSid: string | undefined;
let oldestAt = Infinity;
for (const [s, e] of perLane) {
if (e.at < oldestAt) {
oldestAt = e.at;
oldestSid = s;
}
}
if (oldestSid === undefined) break;
perLane.delete(oldestSid);
}
perLane.set(sid, { sid, boundaryFp, at: now });
stats.learned++;
stats.lanes = lanes.size;
stats.sessions = [...lanes.values()].reduce((n, l) => n + l.size, 0);
}

/**
* Recall (attribution missing): the UNIQUE remembered session on this lane
* whose boundary fingerprint is contained in the incoming history. Undefined
* = no evidence, keep today's behavior.
*/
export function recallConversation(laneKey: string, historyFps: Set<string>): string | undefined {
const now = Date.now();
sweep(now);
const perLane = lanes.get(laneKey);
if (perLane === undefined || perLane.size === 0) {
stats.rejectedNoLane++;
return undefined;
}
const hits: string[] = [];
for (const entry of perLane.values()) {
if (historyFps.has(entry.boundaryFp)) hits.push(entry.sid);
}
if (hits.length === 0) {
stats.rejectedNoBoundary++;
return undefined;
}
if (hits.length > 1) {
stats.rejectedAmbiguous++;
return undefined;
}
// LRU touch so an active session survives idle siblings.
const entry = perLane.get(hits[0]);
if (entry !== undefined) {
perLane.delete(hits[0]);
entry.at = now;
perLane.set(hits[0], entry);
}
stats.recalled++;
return hits[0];
}

export function conversationRecallStats(): Readonly<ConversationRecallStats> {
return { ...stats };
}

export function __resetConversationRecallForTests(): void {
lanes.clear();
stats.lanes = 0;
stats.sessions = 0;
stats.learned = 0;
stats.recalled = 0;
stats.rejectedNoLane = 0;
stats.rejectedNoBoundary = 0;
stats.rejectedAmbiguous = 0;
stats.expired = 0;
}

/** Test seam: age every entry by the given ms (TTL expiry scenarios). */
export function __ageConversationRecallForTests(ms: number): void {
for (const perLane of lanes.values()) {
for (const entry of perLane.values()) entry.at -= ms;
}
}
Loading
Loading