diff --git a/PLUGIN.md b/PLUGIN.md index d12ef260a1..967e73451a 100644 --- a/PLUGIN.md +++ b/PLUGIN.md @@ -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 (`|sub:`) 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. diff --git a/kernel/package-lock.json b/kernel/package-lock.json index da011d94e1..4c5e2d79e9 100644 --- a/kernel/package-lock.json +++ b/kernel/package-lock.json @@ -1,12 +1,12 @@ { "name": "acp-kernel", - "version": "0.0.164", + "version": "0.0.165", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acp-kernel", - "version": "0.0.164", + "version": "0.0.165", "license": "MIT", "devDependencies": { "@types/node": "^22.0.0", diff --git a/package-lock.json b/package-lock.json index 380212c96e..15a6e3f4e9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.163", + "version": "0.0.165", "dev": true, "license": "MIT", "devDependencies": { diff --git a/reference/architecture.md b/reference/architecture.md index 95675fb9c9..30535e7aab 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -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 @@ -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. diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index 19a4494cd8..c0e1175754 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -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 = 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; @@ -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); }); } diff --git a/src/plugin.ts b/src/plugin.ts index 5f70c8a9f2..024627f767 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -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"; @@ -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 (|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(); + 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 diff --git a/src/server/admin.ts b/src/server/admin.ts index bd0fb963e9..fb583dd2d1 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -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"; @@ -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 diff --git a/src/session-delete.ts b/src/session-delete.ts new file mode 100644 index 0000000000..d0340d7254 --- /dev/null +++ b/src/session-delete.ts @@ -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 `|sub:` (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 { + 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 }; +} diff --git a/tests/dsh-native.test.ts b/tests/dsh-native.test.ts index 4392cba37e..7d02919164 100644 --- a/tests/dsh-native.test.ts +++ b/tests/dsh-native.test.ts @@ -5,7 +5,7 @@ import os from "node:os"; import path from "node:path"; import http from "node:http"; import { pathToFileURL } from "node:url"; -import { apply, planNativeDsh, shouldBootstrapNativeDsh, persistClientEvent, mediaBytesOfWireBody, bodyProvablyOverWindow, _attributionHealthForTest, _resetAttributionHealthForTest, _registerStateForTest, _resetRegisterForTest, _setModelInfoForTest, _setSpawnForTest, _setThrewRetryForTest, _settleNativeForTest, _stateHeadersForTest, _stateRespawnForTest, _stateTakeoverGateForTest, _stateToolsReadyForTest, _stateBeforeSendForTest, _stateOnResponseForTest, _noteRoutedForTest, _resetRoutedForTest, _resetWebProfileWarningForTest, _resetNonWebTraceForTest, _resetTitlesForTest, type PluginContext } from "../src/agent/dsh-native.ts"; +import { apply, planNativeDsh, shouldBootstrapNativeDsh, persistClientEvent, mediaBytesOfWireBody, bodyProvablyOverWindow, _attributionHealthForTest, _resetAttributionHealthForTest, _registerStateForTest, _resetRegisterForTest, _setModelInfoForTest, _setSpawnForTest, _setThrewRetryForTest, _settleNativeForTest, _stateHeadersForTest, _stateRespawnForTest, _stateTakeoverGateForTest, _stateToolsReadyForTest, _stateBeforeSendForTest, _stateOnResponseForTest, _noteRoutedForTest, _resetRoutedForTest, _resetWebProfileWarningForTest, _resetNonWebTraceForTest, _resetTitlesForTest, isDshSessionDeleteEvent, type PluginContext } from "../src/agent/dsh-native.ts"; import { __resetIncrementalClientForTests } from "../src/agent/incremental-client.ts"; import { isDshCompactionActive, _resetDshCompactionVerdictForTest } from "../src/agent/dsh-compaction-disable.ts"; import { once } from "node:events"; @@ -483,7 +483,9 @@ type NameCall = { conversationId: string; name: string }; type MockAttributionCall = { agent: string; state: string; refusals: number; since: number; error?: string; endpoint?: string }; -function mockBiliHandler(toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>, statusResponder?: (url: string) => unknown | undefined, nameCalls?: NameCall[], nameStatus?: number, turnEnabled?: boolean, attributionCalls?: MockAttributionCall[], holdManifest?: () => Promise | void): (req: http.IncomingMessage, res: http.ServerResponse) => void { +type DeleteCall = { conversationId: string }; + +function mockBiliHandler(toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>, statusResponder?: (url: string) => unknown | undefined, nameCalls?: NameCall[], nameStatus?: number, turnEnabled?: boolean, attributionCalls?: MockAttributionCall[], holdManifest?: () => Promise | void, deleteCalls?: DeleteCall[]): (req: http.IncomingMessage, res: http.ServerResponse) => void { const manifestTools: MockTool[] = [ { name: "compress", @@ -506,6 +508,19 @@ function mockBiliHandler(toolCalls: Array<{ conversationId: string; tool: string }); return; } + if (url === "/__bili/plugin/delete") { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + if (deleteCalls !== undefined) { + const parsed = JSON.parse(body) as { conversationId?: unknown }; + deleteCalls.push({ conversationId: typeof parsed.conversationId === "string" ? parsed.conversationId : "" }); + } + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, deleted: [], deferred: [] })); + }); + return; + } if (url === "/__bili/plugin/manifest") { // #3616: optional hold — keeps the version probe / registration // manifest IN FLIGHT so a suite can suspend one world's recovery @@ -578,8 +593,8 @@ function mockBiliHandler(toolCalls: Array<{ conversationId: string; tool: string }; } -function startMockProxy(toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>, statusResponder?: (url: string) => unknown | undefined, nameCalls?: NameCall[], nameStatus?: number, turnEnabled?: boolean, attributionCalls?: MockAttributionCall[], holdManifest?: () => Promise | void): Promise<{ origin: string; close: () => void }> { - const server = http.createServer(mockBiliHandler(toolCalls, statusResponder, nameCalls, nameStatus, turnEnabled, attributionCalls, holdManifest)); +function startMockProxy(toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>, statusResponder?: (url: string) => unknown | undefined, nameCalls?: NameCall[], nameStatus?: number, turnEnabled?: boolean, attributionCalls?: MockAttributionCall[], holdManifest?: () => Promise | void, deleteCalls?: DeleteCall[]): Promise<{ origin: string; close: () => void }> { + const server = http.createServer(mockBiliHandler(toolCalls, statusResponder, nameCalls, nameStatus, turnEnabled, attributionCalls, holdManifest, deleteCalls)); return new Promise((resolve) => { server.listen(0, "127.0.0.1", () => { const addr = server.address() as { port: number }; @@ -2891,6 +2906,53 @@ test("explicit attach keeps the DSH tool base when a late routed model origin de } }); +test("#2935: session deletion events co-delete via /__bili/plugin/delete; non-deletion events never do", async () => { + const names: NameCall[] = []; + const deletes: DeleteCall[] = []; + const proxy = await startMockProxy([], undefined, names, undefined, undefined, undefined, undefined, deletes); + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-delete-")); + try { + await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin }, async () => { + _resetRegisterForTest(proxy.origin); + _resetTitlesForTest(); + const ctx = mockCtx(); + apply(ctx); + await waitFor(() => ctx.registeredTools.length === 1, "manifest tool registration"); + + // nested session/event deletion type -> teardown POST + ctx.emit("session/event", { id: "s-del" }, { type: "session/deleted" }); + await waitFor(() => deletes.length === 1, "delete POST"); + assert.deepEqual(deletes[0], { conversationId: "s-del" }); + + // top-level session/deleted event -> teardown POST + ctx.emit("session/deleted", { id: "s-top" }); + await waitFor(() => deletes.length === 2, "top-level delete POST"); + assert.deepEqual(deletes[1], { conversationId: "s-top" }); + + // non-deletion events must leave the delete lane alone + ctx.emit("session/event", { id: "s-t" }, { type: "session/title", data: { title: "X", messageSeqs: [1], source: { kind: "user" } } }); + ctx.emit("session/event", { id: "s-t" }, { type: "message/append", data: {} }); + await waitFor(() => names.length === 1, "title POST on its own lane"); + assert.equal(deletes.length, 2, "no spurious delete POST for non-deletion events"); + }); + } finally { + proxy.close(); + rmrf(home); + _resetRegisterForTest(undefined); + _resetTitlesForTest(); + } +}); + +test("#2935: isDshSessionDeleteEvent matches only explicit per-session destructive types", () => { + assert.equal(isDshSessionDeleteEvent("session/deleted"), true); + assert.equal(isDshSessionDeleteEvent("session/removed"), true); + assert.equal(isDshSessionDeleteEvent("deleted"), true); + assert.equal(isDshSessionDeleteEvent("session/title"), false); + assert.equal(isDshSessionDeleteEvent("message/append"), false); + assert.equal(isDshSessionDeleteEvent(undefined), false); + assert.equal(isDshSessionDeleteEvent(42), false); +}); + // — #2604 host-title channel ———————————————————————————————————————————————— test("#2604: session/title events push the host name to /__bili/plugin/session-name; deduped, rename re-pushes", async () => { diff --git a/tests/issue2935-session-delete.test.ts b/tests/issue2935-session-delete.test.ts new file mode 100644 index 0000000000..3bc65528c6 --- /dev/null +++ b/tests/issue2935-session-delete.test.ts @@ -0,0 +1,237 @@ +import assert from "node:assert"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; +import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +// Isolate state + config so a developer's real billion-context.json and +// session files never leak into the rig (wiring-test pattern). +const HOME = mkdtempSync(path.join(tmpdir(), "bc-2935-")); +process.env.HOME = HOME; +process.env.BILI_CONFIG_FILE = path.join(HOME, "billion-context.json"); + +// Imported AFTER the env isolation above. +const { defaultConfig } = await import("acp-kernel"); +const { startServer } = await import("../src/server.ts"); +const { SessionStore, _setStoreForTest } = await import("../src/persist.ts"); +const { _resetPluginStateForTest } = await import("../src/plugin.ts"); +const { _resetSessionsForTest, getSession, listSessions, peekSession } = await import("../src/session.ts"); +const { deleteSessionArtifacts, personaForkIds } = await import("../src/session-delete.ts"); +const { prefixAffinity } = await import("../src/prefix-affinity.ts"); +const { restoreExportDir } = await import("../src/image-restore.ts"); +import type { ProxyOptions } from "../src/config.ts"; + +function listen(server: http.Server): Promise { + if (server.listening) return Promise.resolve(); + return once(server, "listening").then(() => undefined); +} + +function textScript(): string { + return [ + "event: message_start\ndata: {\"type\":\"message_start\"}\n\n", + "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n", + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"ok\"}}\n\n", + "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n", + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":3}}\n\n", + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n", + ].join(""); +} + +test("personaForkIds: only |sub:* descendants match (#2935)", () => { + const sessions = [ + { id: "conv-1" }, + { id: "conv-1|sub:aaa" }, + { id: "conv-1|sub:bbb" }, + { id: "conv-10" }, // shares the bare prefix "conv-1" but is NOT a fork + { id: "conv-1x" }, + { id: "other|sub:zzz" }, + ]; + assert.deepEqual(personaForkIds("conv-1", sessions), ["conv-1|sub:aaa", "conv-1|sub:bbb"]); + assert.deepEqual(personaForkIds("other", sessions), ["other|sub:zzz"]); + assert.deepEqual(personaForkIds("nope", sessions), []); +}); + +test("deleteSessionArtifacts tears down every artifact for a resident session (#2935)", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "bc-2935-store-")); + const store = new SessionStore({ dir, debounceMs: 1 }); + _setStoreForTest(store); + _resetSessionsForTest(); + try { + const meta = { protocol: "anthropic", upstreamOrigin: "https://api.example.com" } as const; + const s = getSession("del-a", meta); + // Seed every co-lifecycle artifact so we can prove each is torn down. + prefixAffinity.note("del-a", 1, "tail-hash-a", ["h1"], true); + assert.ok(prefixAffinity.trackedSessionIds().includes("del-a"), "affinity chain tracked"); + const spill = restoreExportDir("del-a"); + mkdirSync(spill, { recursive: true }); + writeFileSync(path.join(spill, "img.bin"), "x"); + assert.ok(existsSync(spill), "image spill present before teardown"); + + // Force the persisted record out so there is something to remove. + await store.writeNow(s); + assert.ok(store.loadSync("del-a", meta) !== null, "session persisted before teardown"); + + const out = await deleteSessionArtifacts("del-a"); + assert.equal(out.deleted, true, "reported deleted"); + assert.equal(out.deferred, false, "not deferred"); + assert.equal(peekSession("del-a"), undefined, "resident dropped from memory"); + assert.equal(store.loadSync("del-a", meta), null, "persisted record removed"); + assert.ok(!existsSync(spill), "image spill dir removed"); + assert.ok(!prefixAffinity.trackedSessionIds().includes("del-a"), "affinity chain forgotten"); + } finally { + _resetSessionsForTest(); + } +}); + +test("deleteSessionArtifacts defers while a request is in-flight, then succeeds (#2935)", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "bc-2935-busy-")); + _setStoreForTest(new SessionStore({ dir, debounceMs: 1 })); + _resetSessionsForTest(); + try { + const s = getSession("del-busy", { protocol: "anthropic", upstreamOrigin: "https://api.example.com" }); + s.inFlight = 1; // simulate an active request holding the session + const busy = await deleteSessionArtifacts("del-busy"); + assert.equal(busy.deleted, false, "not deleted while busy"); + assert.equal(busy.deferred, true, "deferred while busy"); + assert.equal(busy.reason, "busy"); + assert.ok(peekSession("del-busy"), "still resident while busy"); + + s.inFlight = 0; + const done = await deleteSessionArtifacts("del-busy"); + assert.equal(done.deleted, true, "deleted once idle"); + assert.equal(peekSession("del-busy"), undefined, "resident dropped after idle"); + } finally { + _resetSessionsForTest(); + } +}); + +type DeleteBody = { ok: boolean; conversationId?: string; deleted?: string[]; deferred?: string[]; error?: string }; + +type Rig = { + proxyUrl: (p: string) => string; + modelUrl: () => string; + closeAll: () => Promise; +}; + +async function startRig(): Promise { + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(textScript()); + }); + }); + upstream.listen(0, "127.0.0.1"); + await listen(upstream); + const upstreamPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + _resetPluginStateForTest(); + _resetSessionsForTest(); + + const opts: ProxyOptions = { + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "l2935-model": { context: 100_000 } } } }, + modelContextLimit: 100_000, + kernelConfig: defaultConfig(100_000), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + log: false, + sessionHeader: "x-acp-session", + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + mitm: { enabled: false, domains: [] }, + }; + const proxy = await startServer(opts); + await listen(proxy); + const proxyPort = (proxy.address() as { port: number }).port; + return { + proxyUrl: (p) => `http://127.0.0.1:${proxyPort}${p}`, + modelUrl: () => `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/v1/messages`, + closeAll: async () => { + await new Promise((resolve, reject) => proxy.close((e) => (e ? reject(e) : resolve()))); + await new Promise((resolve, reject) => upstream.close((e) => (e ? reject(e) : resolve()))); + }, + }; +} + +async function register(rig: Rig, conversationId: string): Promise { + const res = await fetch(rig.proxyUrl("/__bili/plugin/register"), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId, agent: "pi" }), + }); + assert.equal(res.status, 200, "register accepted"); +} + +async function postDelete(rig: Rig, rawBody: string): Promise<{ status: number; body: DeleteBody }> { + const res = await fetch(rig.proxyUrl("/__bili/plugin/delete"), { + method: "POST", + headers: { "content-type": "application/json" }, + body: rawBody, + }); + return { status: res.status, body: (await res.json()) as DeleteBody }; +} + +test("POST /__bili/plugin/delete: validation, host-session cleanup, fork cascade, sibling isolation (#2935)", async () => { + const rig = await startRig(); + try { + // --- validation (synchronous 400s) --- + assert.equal((await postDelete(rig, "not json")).status, 400, "invalid JSON rejected"); + assert.equal((await postDelete(rig, "{}")).status, 400, "missing conversationId rejected"); + assert.equal((await postDelete(rig, JSON.stringify({ conversationId: "" }))).status, 400, "blank conversationId rejected"); + + // --- unknown conversation: idempotent no-op, still 200 --- + const none = await postDelete(rig, JSON.stringify({ conversationId: "never-existed" })); + assert.equal(none.status, 200); + assert.deepEqual(none.body.deleted, [], "nothing deleted for unknown conversation"); + assert.deepEqual(none.body.deferred, [], "nothing deferred for unknown conversation"); + + // --- real host-created session: register + one model turn, then delete --- + const before = new Set(listSessions().map((s) => s.id)); + await register(rig, "del-e2e"); + await fetch(rig.modelUrl(), { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin-conversation": "del-e2e" }, + body: JSON.stringify({ model: "l2935-model", max_tokens: 8192, stream: true, messages: [{ role: "user", content: "hello" }] }), + }); + const created = listSessions().find((s) => !before.has(s.id)); + assert.ok(created, "the model turn created a session bound to the conversation"); + + const delHost = await postDelete(rig, JSON.stringify({ conversationId: "del-e2e" })); + assert.equal(delHost.status, 200); + assert.ok(delHost.body.deleted?.includes(created.id), "host session deleted by its conversation id"); + assert.equal(peekSession(created.id), undefined, "host session dropped from memory"); + + // --- fork cascade + independent-sibling isolation (resident ids) --- + getSession("conv-x", { protocol: "anthropic", upstreamOrigin: "https://api.example.com" }); + getSession("conv-x|sub:fp1", { protocol: "anthropic", upstreamOrigin: "https://api.example.com" }); + getSession("conv-y", { protocol: "anthropic", upstreamOrigin: "https://api.example.com" }); + + const delX = await postDelete(rig, JSON.stringify({ conversationId: "conv-x" })); + assert.equal(delX.status, 200); + assert.ok(delX.body.deleted?.includes("conv-x"), "parent conversation deleted"); + assert.ok(delX.body.deleted?.includes("conv-x|sub:fp1"), "persona fork cascades with its parent"); + assert.ok(!delX.body.deleted?.includes("conv-y"), "independent sibling NOT deleted"); + assert.equal(peekSession("conv-x"), undefined, "parent gone from memory"); + assert.equal(peekSession("conv-x|sub:fp1"), undefined, "fork gone from memory"); + assert.ok(peekSession("conv-y"), "independent sibling survives"); + } finally { + await rig.closeAll(); + _resetSessionsForTest(); + _resetPluginStateForTest(); + } +});