Skip to content
Open
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
12 changes: 12 additions & 0 deletions PLUGIN.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,18 @@ Marker divert (#3248 phase 2 — native extensions): instead of switching the pr

中文集成要点:fork 协议现为 2(服务端同时接受 1);先读取 manifest 能力及 snapshot,按原文、role、工具身份确认匹配前缀,仅提交该前缀的 orderedMessages,不猜测多模态分支点。被 `compress.protectedTools` 硬排除的消息在两个数组中均为 `"ref": null`(参与顺序与身份、无地址 ref),与其他前缀条目一样逐字提交;ref 合法值仅 `mNNNNN` 字符串或 `null`。父 revision 变化必须重新取快照并重新匹配。子会话使用独立稳定 id,首次请求可追加尚未出站的模型回复,不能重置继承的 refs/blocks。手动摘要使用 snapshot 的 refs 和 `expectedRevision: snapshot.parentRevision` 调用公开 tool;摘要期间历史发生变化时返回 409,不执行旧摘要。状态栏读取 `contextTokens`、`contextTokensSource`、`contextTokensAt`、`model`、`contextLimit`、`contextGeneration`、`sessionId` 与 `sessionRevision`,不得用累计账单 input/cache 冒充有效上下文。手动 compress/decompress 后为独立时间及 generation 的 estimate,不改累计账单或 last-usage 基线;下一次正数 usage 才恢复 usage,零值或缺失 usage 不得复活旧观测。未知来源返回 unavailable,tokens/time/generation 为 null。

### 9. `POST /__bili/plugin/delete`

Co-delete a conversation's compression artifacts when the **host** deletes the conversation itself (dsh / other agents). This is the host-side counterpart to a manual delete — there is deliberately **no web-UI delete** (accidental-deletion guard, #2935); only a same-host plugin may call it. Same admin gate + request-body limit as every `/__bili/plugin/*` route.

```json
{ "conversationId": "the value you send as x-bili-plugin-conversation" }
```

Effect: removes every artifact bound to that conversation's session id(s) — the session file, its lossless CCR content-store companion, any image-spill directory, unified-store rows (+ CAS refcount release), the in-memory resident session, and the prefix-affinity chain. Persona forks (`<id>|sub:<fp>`) cascade with their parent; independent child conversations (own ids) are left untouched. Deletion is compression-state-agnostic — a compressed session's data is exactly what this reclaims. A session with an in-flight request or a pending debounced save is **deferred**, not deleted (removing its file under a live writer would resurrect it on the next flush); the caller's next trigger retries once idle.

The response is always `200` `{ ok, conversationId, deleted[], deferred[] }`, even when nothing was resident — the caller is expected to be a periodic reconcile that must not treat "nothing here" as an error. Errors: `400` invalid JSON / missing `conversationId`.

## Security

- The tool endpoints sit behind the `/__bili/` admin gate: loopback-only + trusted-origin. A plugin on the same machine as the proxy can call them; nothing else can.
Expand Down
4 changes: 2 additions & 2 deletions kernel/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-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion reference/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ billion-context/
│ ├── session.ts # Session model + in-memory store (bounded, MAX_SESSIONS)
│ ├── session-id.ts # Session identity: client value verbatim + persona fork fingerprint
│ ├── session-gc.ts # Session-file GC, opt-in (sessions.gc.* / BILI_SESSION_GC*) (#1082)
│ ├── session-delete.ts # Co-delete a conversation's compression artifacts on host-side delete (#2935)
│ ├── persist.ts # On-disk session persistence (kernel StateStore)
│ ├── persist-eperm.ts # EPERM/EACCES write-failure alert layer (#362)
│ ├── encrypt.ts # At-rest encoding: AES-256-GCM (#708) + zstd (#1080), independent
Expand Down Expand Up @@ -211,7 +212,7 @@ When navigating this codebase, these are the load-bearing entry points:
- **Knobs** — every behavior knob resolves through `src/knobs.ts` (env > config file > default, #2030). Never add a new `process.env` read in a leaf module — see AGENTS.md "Environment Variable Discipline".
- **Update path** — `src/update.ts` is deliberately self-contained and conservative; it installs via tarball extraction (not `npm install`) to avoid lifecycle-script surprises on user machines. It is load-bearing infrastructure: changes require a no-op validation release first (§5).
- **Agent plugins** — `src/agent/*.ts` are thin host-specific adapters; shared logic lives in `src/agent/shared.ts`. Each host has a `-native.ts` bootstrap gate variant.
- **Persistence** — `src/persist.ts` wraps the acp-kernel `StateStore`; `src/session.ts` holds the in-memory session pool. Session identity rules: `src/session-id.ts`.
- **Persistence** — `src/persist.ts` wraps the acp-kernel `StateStore`; `src/session.ts` holds the in-memory session pool. Session identity rules: `src/session-id.ts`. Host-side deletion teardown (co-delete a conversation's artifacts): `src/session-delete.ts` (#2935).
- **会话派生缓存** — `Session.transient` 持有插件工具视图与诊断请求副本;随会话淘汰释放,也纳入会话对象图的字节计量。它不写入持久化记录或上游协议;诊断截段独立复制 UTF-16 内容,避免保留完整请求底层字符串(#2920)。
- **Wire fidelity** — `src/stream-*.ts` files handle per-protocol streaming transformation. The invariant: never alter upstream protocol shape beyond intended injection (§7.3).
- **E2E regression** — `tests/e2e/` contains real-client suites (codex, opencode, pi, dsh) plus hermetic lanes (registry, advisory-rollback, release-canary, opencode WS, image billing); each carries its own skip gate — read the test header for the exact env var.
Expand Down
50 changes: 46 additions & 4 deletions src/agent/dsh-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,39 @@ function reportDshSessionName(base: string | undefined, sid: string | undefined,
});
}

// #2935: co-delete a conversation's compression artifacts when the HOST deletes
// the conversation. Fire-and-forget like the title push above — a delete must
// never throw into the host event bus. Unlike titles there is no dedup/re-arm:
// a deletion is one-shot per conversation and the endpoint is idempotent, so a
// missed push (proxy down at that instant) just leaves bounded artifacts that
// converge on the opt-in GC (#1082).
function reportDshSessionDelete(base: string | undefined, sid: string | undefined): void {
if (base === undefined || typeof sid !== "string" || sid.length === 0) return;
fetch(`${base}/__bili/plugin/delete`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ conversationId: sid }),
signal: AbortSignal.timeout(5000),
}).catch(() => {
// fire-and-forget: nothing to re-arm (a deleted session stays deleted)
});
}

// #2935: the host shim types the session-bus payload `type` as `unknown` and
// only `session/title` is referenced in-repo, so the exact deletion spelling is
// not discoverable from this repo alone. Match the convention-consistent
// destructive spellings as an EVIDENCE-PERMITLIST (not a substring filter):
// only these explicit per-session signals act, so a wrong guess degrades to a
// no-op rather than a spurious delete. If dsh's real spelling differs, add it
// here — the teardown endpoint is idempotent.
const DSH_SESSION_DELETE_TYPES: ReadonlySet<string> = new Set([
"session/deleted", "session/removed", "session/cleared",
"deleted", "removed", "cleared",
]);
export function isDshSessionDeleteEvent(type: unknown): boolean {
return typeof type === "string" && DSH_SESSION_DELETE_TYPES.has(type);
}

function seedDshSessionTitle(session: DshSessionLike): void {
const sid = typeof session.id === "string" ? session.id : undefined;
const get = titleServices.sessionTitle?.get;
Expand Down Expand Up @@ -1770,10 +1803,19 @@ export function apply(ctx: PluginContext): void {
seedDshSessionTitle(session);
});
ctx.on("session/event", (session: { id?: unknown }, event: { type?: unknown; data?: { title?: unknown } }) => {
if (event?.type !== "session/title") return;
const title = event.data?.title;
if (typeof title !== "string" || title.length === 0) return;
reportDshSessionName(register.base, typeof session.id === "string" ? session.id : undefined, title);
const sid = typeof session.id === "string" ? session.id : undefined;
const type = event?.type;
if (type === "session/title") {
const title = event.data?.title;
if (typeof title === "string" && title.length > 0) reportDshSessionName(register.base, sid, title);
} else if (isDshSessionDeleteEvent(type)) {
reportDshSessionDelete(register.base, sid);
}
});
// #2935: some hosts surface deletion as its own top-level event (parallel
// to session/created) rather than a nested session/event type — cover both.
ctx.on("session/deleted", (session: DshSessionLike) => {
reportDshSessionDelete(register.base, typeof session.id === "string" ? session.id : undefined);
});
}

Expand Down
58 changes: 58 additions & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { normalizeSseLineEndings, finalizeSseLineEndings } from "./sse-util.js";
import { composeStreamFilters, containsBiliInternalText, containsEchoResidue, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, containsToolCallXmlFragment, createBiliArtifactFilter, createIdentityStreamFilter, createMarkerLineFilter, createTagEchoFilter, isOrphanMarkupText, mayStartBiliInternal, mayStartDegenerateRenderTag, mayStartMarkerLine, mayStartRenderTag, mayStartToolCallEmission, stripAcpTags, stripAnthropicText, stripOpenaiChatText, stripResponsesText, type TagEchoFilter } from "./loop/tag-echo-filter.js";
import { log as loggerLog } from "./logger.js";
import { scanModelOutputForPhantomAttachments } from "./phantom-attachment.js";
import { deleteSessionArtifacts, personaForkIds } from "./session-delete.js";
import { ccrEnabled, ccrLoopConfig, contentStoreOf, retrieveToolName } from "./store.js";
import { emitStreamError, emitUpstreamTruncation } from "./stream-error.js";
import type { TruncationDiag } from "./stream-error.js";
Expand Down Expand Up @@ -886,6 +887,63 @@ export function handlePluginSessionName(payload: string, res: import("node:http"
res.end(JSON.stringify({ ok: true, conversationId }));
}

// #2935: host-side conversation deletion (dsh / other agents) co-deletes this
// conversation's compression artifacts. Loopback-gated like every /__bili/
// route (src/server/admin.ts). Fires only for THIS conversation's own sessions
// plus its persona forks (<id>|sub:*); independent child conversations keep
// their own ids and are left alone. Fire-and-forget friendly: always 200 with
// what was actually removed, even when nothing was resident (idempotent no-op),
// because the caller is a periodic reconcile that must not treat "nothing here"
// as an error.
export function handlePluginDelete(payload: string, res: import("node:http").ServerResponse): void {
let parsed: { conversationId?: unknown };
try {
parsed = JSON.parse(payload) as { conversationId?: unknown };
} catch {
res.writeHead(400, { "content-type": "application/json" });
res.end(JSON.stringify({ ok: false, error: "invalid JSON body" }));
return;
}
const conversationId = typeof parsed.conversationId === "string" ? parsed.conversationId.trim() : "";
if (!conversationId) {
res.writeHead(400, { "content-type": "application/json" });
res.end(JSON.stringify({ ok: false, error: "conversationId is required" }));
return;
}
void (async () => {
const resident = listSessions();
const targets = new Set<string>();
for (const s of resident) if (s.id === conversationId) targets.add(s.id);
for (const id of personaForkIds(conversationId, resident)) targets.add(id);
// The map may bind this conversation to a session whose id differs from
// the verbatim id (canonical/pck alias) — sweep that too.
const entry = conversations.get(conversationId);
if (entry) {
const bound = peekSession(entry.sessionId) ?? findSessionByCanonicalId(entry.sessionId);
if (bound) targets.add(bound.id);
}
const canonical = findSessionByCanonicalId(conversationId);
if (canonical) targets.add(canonical.id);
const deleted: string[] = [];
const deferred: string[] = [];
for (const id of [...targets]) {
const outcome = await deleteSessionArtifacts(id);
if (outcome.deleted) deleted.push(id);
else deferred.push(id);
}
for (const key of [...conversations.keys()]) {
if (key === conversationId || key.startsWith(`${conversationId}|sub:`)) conversations.delete(key);
}
flushConversations();
loggerLog("info", `[plugin-delete] conversation ${conversationId}: deleted=[${deleted.join(", ")}] deferred=[${deferred.join(", ")}]`);
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ ok: true, conversationId, deleted, deferred }));
})().catch((err: unknown) => {
res.writeHead(500, { "content-type": "application/json" });
res.end(JSON.stringify({ ok: false, error: err instanceof Error ? err.message : String(err) }));
});
}

// #1685: the conversation_id tool parameter is GONE from the manifest — the
// model must never see or echo a conversation id (zero-injection identity:
// the proxy routes by outbound tool_use witness / body id / single-active
Expand Down
16 changes: 15 additions & 1 deletion src/server/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { detectCostAdvisories } from "../plugin-advisory.js";
import { fetchWithTimeout } from "../fetch-util.js";
import { log as loggerLog, getLogPath } from "../logger.js";
import { getBlindTunnelStats } from "../mitm.js";
import { handlePluginAttribution, handlePluginCompact, handlePluginFork, handlePluginManifest, handlePluginRegister, handlePluginRuntimeInfo, handlePluginSessionName, handlePluginSnapshot, handlePluginStatus, handlePluginTool } from "../plugin.js";
import { handlePluginAttribution, handlePluginCompact, handlePluginDelete, handlePluginFork, handlePluginManifest, handlePluginRegister, handlePluginRuntimeInfo, handlePluginSessionName, handlePluginSnapshot, handlePluginStatus, handlePluginTool } from "../plugin.js";
import { parseAgentProviderReport, recordAgentProviders, agentProviderRecipes, sanitizeAgentProviderField } from "../agent-providers.js";
import { defaultLogFile } from "../paths.js";
import { getUpdateVisibility, updateBannerPayload } from "../update-notes.js";
Expand Down Expand Up @@ -817,6 +817,20 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv
return;
}
}
if (req.method === "POST" && req.url === "/__bili/plugin/delete") {
// #2935: host-side conversation deletion co-deletes this conversation's
// compression artifacts. Inherits the /__bili/ loopback + trusted-origin
// gate above — no web-UI surface is exposed for it (anti-misfire).
try {
const body = await readBody(req);
handlePluginDelete(body.toString("utf8"), res);
return;
} catch (err) {
res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" });
res.end(JSON.stringify({ ok: false, error: String(err) }));
return;
}
}
// Unknown /__bili/ or /__acp/ path → 404 locally. These are bili's own
// management prefixes; forwarding would leak the internal path to the
// upstream (which 403s it) — #346. #3100: a frozen pre-update process 404s
Expand Down
55 changes: 55 additions & 0 deletions src/session-delete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// #2935: explicit per-session artifact teardown, driven by a host-side
// conversation deletion (dsh / other agents via POST /__bili/plugin/delete).
// Single owner of the "remove every artifact bound to one session id" routine
// so all callers tear down the same complete set (session file + CCR store +
// image spill + unified rows + resident memory + prefix-affinity).
import { rm } from "node:fs/promises";
import { dropSessionForGc, peekSession } from "./session.js";
import { getStore } from "./persist.js";
import { restoreExportDir } from "./image-restore.js";
import { prefixAffinity } from "./prefix-affinity.js";
import { log as loggerLog } from "./logger.js";

interface DeleteSessionOutcome {
deleted: boolean;
deferred: boolean;
reason?: string;
}

/** Persona forks live under `<baseId>|sub:<fp>` (session-id.ts
* subagentNamespace anchor semantics): pure derivatives of one conversation,
* so they die with it. Independent child conversations (opencode subagent /
* fork children) carry their OWN ids and are deliberately excluded here. */
export function personaForkIds(baseId: string, sessions: Iterable<{ id: string }>): string[] {
const prefix = `${baseId}|sub:`;
const out: string[] = [];
for (const s of sessions) if (s.id.startsWith(prefix)) out.push(s.id);
return out;
}

/** Remove every artifact bound to one resident-or-persisted session id.
* Defers (does not delete) while a request is in-flight or a debounced save
* is armed — removing the file under an active writer would resurrect it on
* the next flush; the caller's next trigger retries once idle. */
export async function deleteSessionArtifacts(sessionId: string): Promise<DeleteSessionOutcome> {
const store = getStore();
const resident = peekSession(sessionId);
if (resident && (resident.inFlight > 0 || store.hasPending(sessionId))) {
loggerLog("info", `[session-delete] deferring ${sessionId}: in-flight or pending save`);
return { deleted: false, deferred: true, reason: "busy" };
}
if (resident) dropSessionForGc(sessionId);
if (store.enabled) {
// #3928 full cascade: clears the unified-store rows too — removeSessionFiles
// alone leaves index.db rows that loadSync still serves from (#2935/master-drift).
await store.removeSession(sessionId);
}
try {
await rm(restoreExportDir(sessionId), { recursive: true, force: true });
} catch (err) {
loggerLog("warn", `[session-delete] image-spill cleanup failed for ${sessionId}: ${err instanceof Error ? err.message : String(err)}`);
}
prefixAffinity.forget(sessionId);
loggerLog("info", `[session-delete] removed artifacts for ${sessionId}`);
return { deleted: true, deferred: false };
}
Loading
Loading