diff --git a/PLUGIN.md b/PLUGIN.md index f84a5043c0..c1efaf5cb4 100644 --- a/PLUGIN.md +++ b/PLUGIN.md @@ -46,6 +46,7 @@ Fetch once at plugin startup. "instructionsMutable": "x-bili-plugin-instructions-mutable" }, "toolEndpoint": "/__bili/plugin/tool", + "protectEndpoint": "/__bili/plugin/protect", "statusEndpoint": "/__bili/plugin/status", "capabilities": { "fork": { "protocolVersion": 1, "endpoint": "/__bili/plugin/fork", "snapshotEndpoint": "/__bili/plugin/snapshot" } @@ -100,7 +101,24 @@ Notes: - `compress` mutates state. Inline `decompress` marks a block restored for re-folding; range restores queue content for the next request. Successful restores also update the estimated context footprint. `search_context` / `acp_status` are read-only. - Errors: `400` invalid JSON / missing `conversationId` / unknown tool, `404` unknown conversation (no model request has arrived with that conversation id yet), `500` execution failure. A **known but disabled** opt-in tool (`absorb` / `acp_rule`) is not an error: it answers `200` with `ok: true` and a `result` explaining that the feature is off on this proxy (#1192). -### 4. `GET /__bili/plugin/status?conversationId=` +### 4. `POST /__bili/plugin/protect` + +Durable-message registration — the **aux** channel of the durable protocol (#2556). The **primary** channel is the content-embedded first-line `\x3cbili-durable\x3e` marker (#2555): protection that travels inside the message bytes survives fork raw-replay, cross-machine exports and proxy mode, where this session-keyed registration cannot. Use the marker when the injector controls the message text; use this endpoint when the text must stay untouched (zero content pollution) or the message was already emitted unmarked. + +```json +{ "conversationId": "the same value you send as x-bili-plugin-conversation", "refs": ["m00017", "m00018"] } +``` + +Response: `{ "ok": true, "action": "protect", "changed": 2, "total": 2 }`. Passing `"clear": true` unregisters the listed refs (`action: "clear"`). Re-registering is idempotent (`changed: 0`). Registration binds the refs' raw content ids into the session's protection set — ids are never reused (kernel contract), so a registration stays pinned to its message even after it dies. Protection takes effect at the next fold; already-folded content is not restored. + +Errors: `400` invalid JSON / missing `conversationId` / `refs` not a non-empty array of `mNNNNN` / `clear` not boolean, `400 UNKNOWN_REF` naming the refs never assigned in this conversation, `404` conversation not resident on this proxy instance. + +Notes: + +- The registration lives in session metadata (persisted across proxy restarts, carried through fork adoption). It is **instance-local truth**: a fork that replays raw history into a fresh conversation, or a host that re-sends history to a new proxy, must re-register — or emit the marker, which needs no registration at all. +- Registered messages are excluded from fold ranges exactly like marker- and lane-protected ones (same `isMessageProtected` guard, composed in both the wire path and the plugin tool path). + +### 5. `GET /__bili/plugin/status?conversationId=` Context-level visibility for plugin UIs (status bars / slash commands): @@ -134,7 +152,7 @@ Forwarding a new model request replaces the previous observation with an estimat `compressibleRanges` is the live kernel recommendation as structured `{startRef, endRef, count, ...}` entries for `sessionRevision`, or `null` if it cannot be computed. An empty list means there is no recommended range. Read the exact conversation without `fallback=latest`, match the snapshot revision and ordered refs, and submit manual `compress` with `expectedRevision`; never parse the human panel or guess a fixed prefix. Hosts must exclude their retained first-user anchor from summaries: kernel pruning retains it even if a recommendation spans it. A concurrent mutation is rejected by the revision guard. -### 5. `POST /__bili/plugin/compact` +### 6. `POST /__bili/plugin/compact` Notify the proxy that the agent performed an **in-session native compaction** (e.g. omp's `/compact` or its auto threshold): the next model request re-sends a shortened history (compaction summary + retained tail) under the SAME conversation id. Fire-and-forget is fine — a failed notification must never break the agent's compaction. @@ -144,11 +162,11 @@ Notify the proxy that the agent performed an **in-session native compaction** (e Effect: the proxy marks a one-shot compaction boundary on the session. On the next model request, blocks that were active before the compaction but no longer anchor into the shortened history are downgraded to a pre-compaction archive (listed by `acp_status` with a reason; `decompress` on one returns an explicit "unavailable" error instead of failing silently), and stale `byRaw`/`byRef` mappings are pruned to the live ids. Errors: `400` invalid JSON / missing `conversationId`, `404` unknown conversation. -### 6. MITM transparent-proxy mode +### 7. MITM transparent-proxy mode The `/bili/` prefix is absent in MITM mode, so URL-based detection cannot work. Instead the proxy's own launcher (`bili pi` / `bili codex` / `bili claude`) exports `BILLION_CONTEXT_PROXY=http://127.0.0.1:` in the child env, next to the `HTTPS_PROXY` + CA vars it already sets. A plugin detects cooperative mode by reading that env var (the proxy origin for all `/__bili/plugin/*` calls); everything else (headers, tool forwarding, status) is identical — the `x-bili-plugin*` headers pass through the MITM tunnel into the same pipeline. This is also where `x-bili-plugin-context-window` matters most: MITM upstreams are often private relays the models.dev registry doesn't know. -### 7. Lifecycle of one compression (what the plugin does) +### 8. Lifecycle of one compression (what the plugin does) 1. Model replies with a native `compress` tool call (args contain `startId`/`endId` refs it read from the tag-annotated context). 2. The agent ends the assistant turn; the plugin's tool handler fires. @@ -158,7 +176,7 @@ The `/bili/` prefix is absent in MITM mode, so URL-based detection cannot work. No special handling is needed for decompression: `decompress` results come back through the same endpoint. -### 8. Public snapshot and fork (protocol 1) +### 9. Public snapshot and fork (protocol 1) Discover `capabilities.fork` from the manifest; do not infer support from the package version. No new configuration is required. These endpoints use the same admin gate and request-body limit as the tool API. diff --git a/src/plugin.ts b/src/plugin.ts index 161b8c7e93..2af955da91 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -795,6 +795,65 @@ export function handlePluginSessionName(payload: string, res: import("node:http" // arbitration; see tool-ring.ts). Wire-mode injection serves the kernel // constants directly, which never carried the param. +/** #2556: server-side durable registration — the AUX channel of the durable + * protocol. The PRIMARY channel is the content-embedded \x3cbili-durable\x3e + * first-line marker (#2555): protection that travels WITH the message bytes + * survives fork raw-replay (#2383), cross-machine exports and proxy mode, + * where this endpoint's session-keyed registration cannot. What registration + * buys instead: zero content pollution (no marker line in host-visible text) + * and post-hoc protection of a message the host did not stamp at emit time. + * Registered raw ids live in session.metadata (persisted, fork-adoption + * clone-safe) and compose into the same isMessageProtected guard as the + * marker and lane guards at BOTH resolution sites (wire path in + * server/handle.ts, read path in session.ts effectiveConfig). Ids are never + * reused (kernel contract), so a registration stays pinned to its message + * even after it dies. */ +export function handlePluginProtect( + payload: string, + res: import("node:http").ServerResponse, + deps: PluginToolDeps, +): void { + let parsed: { conversationId?: unknown; refs?: unknown; clear?: unknown }; + try { + parsed = JSON.parse(payload) as { conversationId?: unknown; refs?: unknown; clear?: unknown }; + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("expected object body"); + } catch { + forkReply(res, 400, { ok: false, code: "INVALID_REQUEST", error: "invalid JSON body" }); + return; + } + const conversationId = typeof parsed.conversationId === "string" ? parsed.conversationId.trim() : ""; + if (!conversationId) return forkReply(res, 400, { ok: false, code: "INVALID_REQUEST", error: "conversationId is required" }); + const clear = parsed.clear === true; + if (parsed.clear !== undefined && typeof parsed.clear !== "boolean") return forkReply(res, 400, { ok: false, code: "INVALID_REQUEST", error: "clear must be a boolean" }); + if (!Array.isArray(parsed.refs) || parsed.refs.length === 0 || parsed.refs.some((r) => typeof r !== "string" || !/^m\d+$/.test(r))) { + return forkReply(res, 400, { ok: false, code: "INVALID_REQUEST", error: "refs must be a non-empty array of ref ids (mNNNNN)" }); + } + const refs = [...new Set(parsed.refs as string[])]; + const session = resolveForkConversation(conversationId); + if (!session) { + return forkReply(res, 404, { ok: false, code: "NOT_FOUND", error: `conversation "${conversationId}" is not resident on this proxy instance` }); + } + const byRef = session.state.messageRefs.byRef; + const unknown = refs.filter((ref) => typeof byRef[ref] !== "string"); + if (unknown.length > 0) { + return forkReply(res, 400, { ok: false, code: "UNKNOWN_REF", error: `unknown refs (never assigned in this conversation): ${unknown.join(", ")}` }); + } + const rawIds = refs.map((ref) => byRef[ref] as string); + const existing = Array.isArray(session.metadata["protectedRawIds"]) ? session.metadata["protectedRawIds"].filter((v): v is string => typeof v === "string") : []; + const set = new Set(existing); + let changed = 0; + for (const raw of rawIds) { + const before = set.size; + if (clear) set.delete(raw); else set.add(raw); + if (set.size !== before) changed++; + } + if (set.size === 0) delete session.metadata["protectedRawIds"]; + else session.metadata["protectedRawIds"] = [...set]; + if (!getStore().flushSync(session)) deps.log("warn", `[plugin] protect ${conversationId}: flush failed; the debounced save will retry`); + deps.log("info", `[plugin] protect ${conversationId}: ${clear ? "cleared" : "registered"} ${changed} ref(s) (${refs.join(", ")}), total protected ${set.size} (#2556)`); + forkReply(res, 200, { ok: true, action: clear ? "clear" : "protect", changed, total: set.size }); +} + export function handlePluginManifest(res: import("node:http").ServerResponse, config: Config): void { // #1192: hosts register whatever the manifest serves verbatim (pi/omp/dsh/ // opencode native plugins, MCP shims), so advertising an opt-in tool this @@ -843,6 +902,7 @@ export function handlePluginManifest(res: import("node:http").ServerResponse, co }, headers: { agent: PLUGIN_AGENT_HEADER, conversation: PLUGIN_CONVERSATION_HEADER, contextWindow: PLUGIN_CONTEXT_WINDOW_HEADER, maxOutput: PLUGIN_MAX_OUTPUT_HEADER, model: PLUGIN_MODEL_HEADER, instructionsMutable: PLUGIN_INSTRUCTIONS_MUTABLE_HEADER }, toolEndpoint: "/__bili/plugin/tool", + protectEndpoint: "/__bili/plugin/protect", statusEndpoint: "/__bili/plugin/status", runtimeInfoEndpoint: "/__bili/plugin/runtime-info", capabilities: { ...(externalSummary ? { externalSummary: { enabled: true, summaryOptional: true, submittedSummary: "hint" } } : {}), fork: { protocolVersion: 1, endpoint: "/__bili/plugin/fork", snapshotEndpoint: "/__bili/plugin/snapshot" } }, diff --git a/src/server/admin.ts b/src/server/admin.ts index 75e46f51c4..e45a4a430a 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 { handlePluginCompact, handlePluginFork, handlePluginManifest, handlePluginRegister, handlePluginRuntimeInfo, handlePluginSessionName, handlePluginSnapshot, handlePluginStatus, handlePluginTool } from "../plugin.js"; +import { handlePluginCompact, handlePluginFork, handlePluginManifest, handlePluginProtect, handlePluginRegister, handlePluginRuntimeInfo, handlePluginSessionName, handlePluginSnapshot, handlePluginStatus, handlePluginTool } from "../plugin.js"; import { parseAgentProviderReport, recordAgentProviders, agentProviderRecipes } from "../agent-providers.js"; import { defaultLogFile } from "../paths.js"; import { getUnrecognizedPathStats } from "./observability.js"; @@ -353,6 +353,19 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv return; } } + if (req.method === "POST" && req.url === "/__bili/plugin/protect") { + // #2556: durable-registration aux channel (marker stays the durable + // truth). Same loopback + trusted-origin gate as the family above. + try { + const body = await readBody(req); + handlePluginProtect(body.toString("utf8"), res, { core, config, log }); + return; + } catch (err) { + res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: false, code: "INVALID_REQUEST", error: String(err) })); + return; + } + } if (req.method === "POST" && req.url === "/__bili/plugin/register") { try { const body = await readBody(req); diff --git a/src/server/handle.ts b/src/server/handle.ts index 00afdd71ee..4749e4a105 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -17,7 +17,7 @@ import { buildIncomingImageIndex, foldAnchoredCutoff, pruneRetrieveImgExports } import { biliDurableMarkerGuard, durableMessageGuards } from "../durable-message-guards.js"; import { biliToolsDeclaredOnWire, countBiliToolUses, evaluateSelfHealRound, nudgeSuppressed, pluginLaneDegraded, pluginLaneRestore } from "../session-self-heal.js"; import { compressBreakerArmed } from "../stream.js"; -import { acquireInFlight, getSession, hasProcessedState, markDirty, peekSession, releaseInFlight, storeEffectiveConfig, tickPostRebuildAnchor, withSessionLock, type Session } from "../session.js"; +import { acquireInFlight, getSession, hasProcessedState, markDirty, peekSession, registeredProtectedRawIds, releaseInFlight, storeEffectiveConfig, tickPostRebuildAnchor, withSessionLock, type Session } from "../session.js"; import { buildCompressSystemPrompt } from "../compress-tool.js"; import { storeEffectiveImageCompression, type ImageCompressionSettings } from "../image-compress.js"; import { storeEffectiveSearchPlanAware } from "../decompress-shared.js"; @@ -1742,8 +1742,12 @@ export async function handle( // both guards at read time, so /__bili/plugin/tool sees them too. storeEffectiveConfig(session, reqConfig); const laneGuard = pluginAgent ? durableMessageGuards[pluginAgent] : undefined; + // #2556: fold in the protect-tool registration set — same read-time + // resolution as session.ts effectiveConfig, so a registration via POST + // /__bili/plugin/protect protects the very next fold on the wire path. + const registered = registeredProtectedRawIds(session); const durableGuard: (msg: CoreMessage) => boolean = - laneGuard ? (msg) => laneGuard(msg) || biliDurableMarkerGuard(msg) : biliDurableMarkerGuard; + laneGuard ? (msg) => laneGuard(msg) || biliDurableMarkerGuard(msg) || registered.has(msg.id) : (msg) => biliDurableMarkerGuard(msg) || registered.has(msg.id); reqConfig = { ...reqConfig, isMessageProtected: durableGuard }; // acquireInFlight must precede the lock so evictOldest() cannot flush // this session between getSession and lock acquisition (inFlight===0 diff --git a/src/session.ts b/src/session.ts index f1710bb84b..8d890e2edf 100644 --- a/src/session.ts +++ b/src/session.ts @@ -438,11 +438,24 @@ export function effectiveConfig(session: Session | undefined, fallback: Config): // mirroring the wire path's composition in server/handle.ts. const lane = typeof session?.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] : undefined; const laneGuard = lane ? durableMessageGuards[lane] : undefined; + // #2556: the aux-channel registration set (POST /__bili/plugin/protect) — + // session-keyed raw ids, persisted via metadata; composes with the marker + // (#2555) and lane guards. Same read-time re-resolution as the guards. + const registered = registeredProtectedRawIds(session); const guard: (msg: CoreMessage) => boolean = - laneGuard ? (msg) => laneGuard(msg) || biliDurableMarkerGuard(msg) : biliDurableMarkerGuard; + laneGuard ? (msg) => laneGuard(msg) || biliDurableMarkerGuard(msg) || registered.has(msg.id) : (msg) => biliDurableMarkerGuard(msg) || registered.has(msg.id); return !base.isMessageProtected ? { ...base, isMessageProtected: guard } : base; } +/** #2556: the protect-tool registration as a membership set. Reading it from + * session.metadata at guard-resolution time (never cached across calls) keeps + * POST /__bili/plugin/protect effective for the next fold without any + * config re-stamping, and metadata persistence carries it across restarts. */ +export function registeredProtectedRawIds(session: Session | undefined): Set { + const raw = session?.metadata["protectedRawIds"]; + return new Set(Array.isArray(raw) ? raw.filter((v): v is string => typeof v === "string") : []); +} + /** #2029: provenance-aware baseline for STATUS readers — acp_status nudge * recompute, plugin live nudge + panel, post-compress tail. Shared by every * status surface so none of them can present an estimate-grade reading as a diff --git a/tests/issue2556-protect-tool.test.ts b/tests/issue2556-protect-tool.test.ts new file mode 100644 index 0000000000..aa4591ffa0 --- /dev/null +++ b/tests/issue2556-protect-tool.test.ts @@ -0,0 +1,317 @@ +// #2556: POST /__bili/plugin/protect — the durable-registration AUX channel. +// The marker (#2555, tests/issue2555-bili-durable-marker.test.ts) stays the +// durable truth; registration buys zero content pollution and post-hoc +// protection of an already-emitted message. This suite pins the endpoint's +// validation contract (loud rejects, no guessing), the fold-time effect in a +// lane-less session (registered raw id survives a positional fold that +// swallows its neighbors), the clear semantics, and the guard composition +// (marker + registration co-protected in one session). +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { resetPersonaAnchorsForTest } from "../src/persona-anchor.ts"; +import { _resetPluginStateForTest } from "../src/plugin.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { getSession, peekSession, _resetSessionsForTest } from "../src/session.ts"; + +process.env.NODE_ENV = "test"; +process.env.BILI_PERSIST = "0"; + +const MODEL = "gpt-test"; +const MAIN_SYSTEM = "You are the main coding agent."; +const DURABLE_MARKED = "\x3cbili-durable kind=\"memory\"\x3e\nmarked channel: never force-push master"; + +function filler(tag: string): string { + return `${tag}-` + "z".repeat(900); +} + +type Rig = { proxyPort: number; upstreamPort: number; proxy: http.Server; upstream: http.Server; bodies: string[] }; + +async function startRig(): Promise { + const bodies: string[] = []; + const upstream = http.createServer((req, res) => { + let b = ""; + req.on("data", (c: Buffer) => (b += c.toString("utf8"))); + req.on("end", () => { + bodies.push(b); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ + id: "chatcmpl-1", + object: "chat.completion", + choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }], + usage: { prompt_tokens: 10, completion_tokens: 3, total_tokens: 13 }, + })); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetSessionsForTest(); + _resetPluginStateForTest(); + resetPersonaAnchorsForTest(); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: {} }, + modelContextLimit: 200_000, + kernelConfig: defaultConfig(200_000, { + preserveRecentMessages: 3, + preserveRecentTokens: 0, + compress: { minCompressRange: 500, maxSummaryLength: 20_000, minSummaryLength: 50 }, + }), + compress: { injectTool: true, injectNudge: false }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + return { proxyPort: (proxy.address() as { port: number }).port, upstreamPort, proxy, upstream, bodies }; +} + +async function closeRig(rig: Rig): Promise { + rig.proxy.close(); + await once(rig.proxy, "close"); + rig.upstream.close(); + await once(rig.upstream, "close"); +} + +/** Refs from NON-SYSTEM message content only (system prompt carries literal + * ACP-tag examples that a whole-body scan would mistake for live refs). */ +function parseRefIds(body: string): string[] { + let messages: Array<{ role?: string; content?: unknown }> = []; + try { + messages = (JSON.parse(body) as { messages?: Array<{ role?: string; content?: unknown }> }).messages ?? []; + } catch { + return []; + } + const text = messages + .filter((m) => m.role !== "system") + .map((m) => (typeof m.content === "string" ? m.content : JSON.stringify(m.content ?? ""))) + .join("\n"); + const ids: string[] = []; + const re = /<(?:acp|dcp-message-id)[^>]*>\s*(m\d+)\s*<\/(?:acp|dcp-message-id)>/g; + let m: RegExpExecArray | null; + while ((m = re.exec(text)) !== null) ids.push(m[1]!); + return ids; +} + +async function protectCall(port: number, body: unknown): Promise<{ status: number; json: Record }> { + const r = await fetch(`http://127.0.0.1:${port}/__bili/plugin/protect`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }); + return { status: r.status, json: (await r.json()) as Record }; +} + +async function compressCall(port: number, conv: string, startId: string, endId: string): Promise<{ status: number; json: Record }> { + const r = await fetch(`http://127.0.0.1:${port}/__bili/plugin/tool`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + conversationId: conv, + tool: "compress", + args: { + topic: "i2556 fold", + content: [{ startId, endId, topic: "i2556 fold", summary: "i2556 fold summary: filler turns were discussed and consumed; nothing else survived this range." }], + }, + }), + }); + return { status: r.status, json: (await r.json()) as Record }; +} + +/** Grow a lane-less conversation; return (bodies, refs) after warmup. */ +async function grow(rig: Rig, conv: string, texts: string[]): Promise { + const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`; + const headers = { "content-type": "application/json", "x-acp-session": conv }; + const msgs: Array<{ role: string; content: string }> = []; + for (const [i, t] of texts.entries()) { + msgs.push({ role: i % 2 === 0 ? "user" : "assistant", content: t }); + const r = await fetch(url, { method: "POST", headers, body: JSON.stringify({ model: MODEL, max_tokens: 64_000, messages: [{ role: "system", content: MAIN_SYSTEM }, ...msgs] }) }); + assert.equal(r.status, 200); + await r.text(); + } +} + +test("protect endpoint: validation contract (loud rejects, no guessing)", async () => { + const rig = await startRig(); + try { + await grow(rig, "i2556-val", [filler("V1"), filler("V2")]); + let r = await protectCall(rig.proxyPort, { refs: ["m00001"] }); + assert.equal(r.status, 400, "conversationId is required"); + assert.equal(r.json.code, "INVALID_REQUEST"); + r = await protectCall(rig.proxyPort, { conversationId: "i2556-val", refs: "m00001" }); + assert.equal(r.status, 400, "refs must be an array"); + r = await protectCall(rig.proxyPort, { conversationId: "i2556-val", refs: [] }); + assert.equal(r.status, 400, "empty refs array rejects"); + r = await protectCall(rig.proxyPort, { conversationId: "i2556-val", refs: ["not-a-ref"] }); + assert.equal(r.status, 400, "malformed ref rejects"); + r = await protectCall(rig.proxyPort, { conversationId: "i2556-val", refs: ["m00001"], clear: "yes" }); + assert.equal(r.status, 400, "clear must be boolean"); + r = await protectCall(rig.proxyPort, { conversationId: "i2556-nope", refs: ["m00001"] }); + assert.equal(r.status, 404, "unknown conversation 404s"); + assert.equal(r.json.code, "NOT_FOUND"); + r = await protectCall(rig.proxyPort, { conversationId: "i2556-val", refs: ["m099999"] }); + assert.equal(r.status, 400, "unknown ref rejects loudly"); + assert.equal(r.json.code, "UNKNOWN_REF"); + assert.ok(String(r.json.error).includes("m099999"), "the unknown ref is named in the error"); + const s = getSession("i2556-val"); + assert.equal(s.metadata["protectedRawIds"], undefined, "no registration leaks on rejects"); + } finally { + await closeRig(rig); + } +}); + +test("lane-less session: a registered ref survives a positional fold; clear re-exposes it", async () => { + const rig = await startRig(); + try { + const conv = "i2556-fold"; + await grow(rig, conv, [ + filler("F1"), filler("A1"), + "KEEP-ME-REGISTERED registered channel: workspace rules live here", + filler("A2"), filler("F3"), filler("A3"), filler("F4"), filler("A4"), filler("F5"), + ]); + const refIds = parseRefIds(rig.bodies.at(-1)!); + assert.ok(refIds.length >= 9, `expected >= 9 refs, got ${refIds.length}`); + // refIds[2] is the third wire message = KEEP-ME-REGISTERED (F1, A1, then it). + const target = refIds[2]!; + assert.ok(rig.bodies.some((b) => b.includes("KEEP-ME-REGISTERED"))); + + let r = await protectCall(rig.proxyPort, { conversationId: conv, refs: [target] }); + assert.equal(r.status, 200); + assert.equal(r.json.changed, 1); + assert.equal(r.json.total, 1); + // registration resolved ref -> raw id into metadata (persisted shape) + const s = getSession(conv); + const registered = s.metadata["protectedRawIds"] as string[]; + assert.equal(registered.length, 1); + assert.equal(s.state.messageRefs.byRef[target], registered[0], "registered raw id must be the ref's own raw id"); + // re-registering the same ref is idempotent + r = await protectCall(rig.proxyPort, { conversationId: conv, refs: [target] }); + assert.equal(r.json.changed, 0, "idempotent registration"); + assert.equal(r.json.total, 1); + + // fold a range that fully covers the registered message + const startId = refIds[0]!; + const endId = refIds[refIds.length - 4]!; + const fold = await compressCall(rig.proxyPort, conv, startId, endId); + assert.ok(fold.status === 200 && fold.json.ok === true, `compress must succeed: ${JSON.stringify(fold.json)}`); + + const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`; + const headers = { "content-type": "application/json", "x-acp-session": conv }; + const post = (msgs: Array<{ role: string; content: string }>) => fetch(url, { method: "POST", headers, body: JSON.stringify({ model: MODEL, max_tokens: 64_000, messages: [{ role: "system", content: MAIN_SYSTEM }, ...msgs] }) }); + const history: Array<{ role: string; content: string }> = [ + { role: "user", content: filler("F1") }, + { role: "assistant", content: filler("A1") }, + { role: "user", content: "KEEP-ME-REGISTERED registered channel: workspace rules live here" }, + { role: "assistant", content: filler("A2") }, + { role: "user", content: filler("F3") }, + { role: "assistant", content: filler("A3") }, + { role: "user", content: filler("F4") }, + { role: "assistant", content: filler("A4") }, + { role: "user", content: filler("F5") }, + { role: "user", content: filler("F6") }, + ]; + const r2 = await post(history); + await r2.text(); + const body = rig.bodies.at(-1)!; + assert.ok(body.includes("[Compressed conversation section]"), "the fold must have happened"); + assert.ok(body.includes("KEEP-ME-REGISTERED"), "the registered message must survive the fold"); + assert.ok(!body.includes("A1-"), "folded neighbors before must be gone"); + assert.ok(!body.includes("F3-"), "folded neighbors after must be gone"); + + // clear re-exposes the message to folding. Re-derive the range from + // the CURRENT wire (fold 1 consumed the old boundary refs) and fold a + // fresh range that covers the still-live target ref. + const r3 = await protectCall(rig.proxyPort, { conversationId: conv, refs: [target], clear: true }); + assert.equal(r3.status, 200); + assert.equal(r3.json.action, "clear"); + assert.equal(r3.json.total, 0); + assert.equal(getSession(conv).metadata["protectedRawIds"], undefined, "empty set removes the key entirely"); + const liveRefs = parseRefIds(rig.bodies.at(-1)!); + assert.ok(liveRefs.includes(target), `target ref ${target} must still be live after fold 1: [${liveRefs.join(",")}]`); + const fold2 = await compressCall(rig.proxyPort, conv, liveRefs[0]!, liveRefs[liveRefs.length - 2]!); + assert.ok(fold2.status === 200 && fold2.json.ok === true, `second compress must succeed: ${JSON.stringify(fold2.json)}`); + const r4 = await post([...history, { role: "user", content: filler("F7") }]); + await r4.text(); + const body2 = rig.bodies.at(-1)!; + assert.ok(!body2.includes("KEEP-ME-REGISTERED"), "after clear the same message folds away — registration was the only protection"); + } finally { + await closeRig(rig); + } +}); + +test("composition: marker channel and registered channel co-protected in one session", async () => { + const rig = await startRig(); + try { + const conv = "i2556-comp"; + await grow(rig, conv, [ + filler("F1"), filler("A1"), + DURABLE_MARKED, + "KEEP-REGISTERED too: second channel", + filler("A2"), filler("F3"), filler("A3"), filler("F4"), filler("A4"), + ]); + const refIds = parseRefIds(rig.bodies.at(-1)!); + const target = refIds[3]!; // KEEP-REGISTERED (4th wire message) + const r = await protectCall(rig.proxyPort, { conversationId: conv, refs: [target] }); + assert.equal(r.status, 200); + const startId = refIds[0]!; + const endId = refIds[refIds.length - 4]!; + const fold = await compressCall(rig.proxyPort, conv, startId, endId); + assert.ok(fold.status === 200 && fold.json.ok === true, JSON.stringify(fold.json)); + const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`; + const headers = { "content-type": "application/json", "x-acp-session": conv }; + const history: Array<{ role: string; content: string }> = [ + { role: "user", content: filler("F1") }, + { role: "assistant", content: filler("A1") }, + { role: "user", content: DURABLE_MARKED }, + { role: "user", content: "KEEP-REGISTERED too: second channel" }, + { role: "assistant", content: filler("A2") }, + { role: "user", content: filler("F3") }, + { role: "assistant", content: filler("A3") }, + { role: "user", content: filler("F4") }, + { role: "assistant", content: filler("A4") }, + { role: "user", content: filler("F5") }, + ]; + const r2 = await fetch(url, { method: "POST", headers, body: JSON.stringify({ model: MODEL, max_tokens: 64_000, messages: [{ role: "system", content: MAIN_SYSTEM }, ...history] }) }); + await r2.text(); + const body = rig.bodies.at(-1)!; + assert.ok(body.includes("[Compressed conversation section]"), "the fold must have happened"); + assert.ok(body.includes("never force-push master"), "marker channel survives (primary)"); + assert.ok(body.includes("KEEP-REGISTERED too"), "registered channel survives (aux)"); + assert.ok(!body.includes("A1-"), "the pre-protected segment folds — the fold is real, not vetoed wholesale"); + } finally { + await closeRig(rig); + } +}); + +test("manifest advertises the protect endpoint", async () => { + const rig = await startRig(); + try { + const r = await fetch(`http://127.0.0.1:${rig.proxyPort}/__bili/plugin/manifest`); + const json = (await r.json()) as { protectEndpoint?: string }; + assert.equal(json.protectEndpoint, "/__bili/plugin/protect"); + } finally { + await closeRig(rig); + } +});