Skip to content
Closed
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
28 changes: 23 additions & 5 deletions PLUGIN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down Expand Up @@ -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=<id>`
### 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=<id>`

Context-level visibility for plugin UIs (status bars / slash commands):

Expand Down Expand Up @@ -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.

Expand All @@ -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:<port>` 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.
Expand All @@ -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.

Expand Down
60 changes: 60 additions & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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" } },
Expand Down
15 changes: 14 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 { 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";
Expand Down Expand Up @@ -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);
Expand Down
8 changes: 6 additions & 2 deletions src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down
15 changes: 14 additions & 1 deletion src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> {
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
Expand Down
Loading
Loading