diff --git a/AGENTS.md b/AGENTS.md
index 5bdabee1cf..7a1b6e42de 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -36,7 +36,7 @@ The full file-by-file map lives in [reference/architecture.md](reference/archite
1. **The in-repo kernel is bundled inline** — `kernel/` (the acp-kernel source, consumed as a `file:` devDependency, #2092) is NOT listed in tsup `external`, so `dist/index.js` is self-contained. Exception: `zod` (exact `4.1.8`, matching the opencode host's own zod so V1 plugin-tool shapes interoperate) is a real dependency and stays external — only `dist/agent/opencode-native.js` imports it (lazily, at plugin-tool registration); `dist/index.js` and every other entry remain zod-free. When zod cannot be resolved at runtime the V1 plugin degrades to plain proxy mode instead of failing. Same for `pi-subagents/` (the billion-context-pi-subagents source, #2384): consumed via a `file:` devDependency and inlined into the pi-lane entries; its own build inlines the `typebox` peer, so those bundles stay self-contained too.
2. **Tags use XML format** — messages carry ACP tags like `m00001` (an opening element with `tokens=`/`type=` attributes wrapping a ref id, closed by its end element). In **source files** these angle brackets MUST be written as hex escapes (`\x3c`, `\x3e`) to avoid tooling that strips well-formed tags.
-3. **Auto-update**: checks npm registry every 3 min by default (`CHECK_INTERVAL_MS = 3*60*1000`, overridable via `update.checkIntervalMs` / `BILI_UPDATE_CHECK_INTERVAL_MS`, #2030); first check per process ignores throttle.
+3. **Auto-update**: checks npm registry every 3 min by default (`CHECK_INTERVAL_MS = 3*60*1000`, overridable via `update.checkIntervalMs` / `BILI_UPDATE_CHECK_INTERVAL_MS`, #2030); first check per process ignores throttle. In plugin mode the injected code lives in the HOST process — new code only takes effect after a host restart, and if the injection breaks at runtime, model traffic goes direct (uncompressed) until the host is restarted; since #3581 that state is visible via the panel banner and `/__bili/status` `attribution` field (README Self-update section).
4. **Tee logger**: all proxy logs go through `src/logger.ts` (file + stderr). Do NOT use `console.error` in server-side modules — use `loggerLog()`.
5. **The kernel lives in-repo; determinism comes from git, not a registry pin (#2092).** The acp-kernel source is vendored under `kernel/` and consumed via `"acp-kernel": "file:./kernel"` (devDependency; inlined into `dist` at build time). A commit IS the pin — there is no registry range left to drift. The kernel keeps its OWN version in `kernel/package.json`: any kernel source change MUST bump it (CI-enforced — see Kernel Boundary below), so accumulated changes can later ship as an independent npm release of `acp-kernel`. `package-lock.json` records the file link and stays committed. Same pattern for `pi-subagents/` (#2384): vendored under `pi-subagents/`, consumed via `"billion-context-pi-subagents": "file:./pi-subagents"`, own version in `pi-subagents/package.json` (CI-enforced — see Pi-Subagents Boundary below).
6. **Single-writer plugin copies (#991)** — every bili presence has exactly ONE writer; mixing writers is what the guard forbids. The canonical statement is the Install-Lane & Update-Ownership Contract below.
diff --git a/README.md b/README.md
index e022fa67b9..a5f9104d76 100644
--- a/README.md
+++ b/README.md
@@ -433,7 +433,7 @@ The proxy checks npm on startup and every 3 minutes; a newer version is installe
While the running process is behind the on-disk install ("stale"), the web UI shows a banner (running vs installed version, auto-restart state) and `GET /__bili/status` returns `{version, diskVersion, stale, autoRestartOnUpdate, advisory, inFlight}` for scripting (`advisory` is the active critical-defect entry or `null`, see below). Disable permanently via `"autoUpdate": false` in config or `ACP_AUTO_UPDATE=0`.
-In **plugin mode** (`bili opencode` / `bili pi` / `bili dsh` — the proxy runs embedded in a long-lived host), "restart bili" means restarting the **host**: the embedded process cannot exit on its own, so a host left open keeps serving whatever code it started with, silently missing every fix auto-update reports as installed (#1603). Enable `--auto-restart-on-update` to have it self-restart at a safe point, or run `/acp` (OpenCode hosts today — pi/dsh coverage tracked in #2084) — the status panel appends a one-line staleness warning (running vs installed version) whenever the on-disk install is ahead of the live process.
+In **plugin mode** (`bili opencode` / `bili pi` / `bili dsh` — the proxy runs embedded in a long-lived host), "restart bili" means restarting the **host**: the embedded process cannot exit on its own, so a host left open keeps serving whatever code it started with, silently missing every fix auto-update reports as installed (#1603). Enable `--auto-restart-on-update` to have it self-restart at a safe point, or run `/acp` (OpenCode hosts today — pi/dsh coverage tracked in #2084) — the status panel appends a one-line staleness warning (running vs installed version) whenever the on-disk install is ahead of the live process. Auto-update only ever replaces disk files and (optionally) the proxy process; **injected code inside the host process only takes effect after the host itself restarts** — so if the injection breaks at runtime mid-session (a disposed agent scope, a disabled plugin), model traffic goes direct and uncompressed until then. Since #3581 this state is visible instead of silent: the web UI shows a "takeover broken" banner (agent + refusal count) whenever a plugin reports its attribution gate degraded while no session is live, and `GET /__bili/status` / `/__bili/overview` expose the per-agent `attribution` state (`ok`/`none`/`threw`, refusal count, first-refusal timestamp).
**Update visibility is silent by default since v0.1.183 (#1977):** routine/recommended releases no longer render an update line on the `/acp` panel footer or in `acp_status` — only a `critical`-tier release surfaces there (`CRITICAL UPDATE READY/AVAILABLE`). The standing ways to check an installed-but-not-restarted release are the stale cues above: web UI banner, the `/acp` one-line warning, and `GET /__bili/status`. Deliberately no always-on nag; the advisory channel (#1481) remains the only auto-visible critical path.
diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts
index f886d852e6..dbe865d8f0 100644
--- a/src/agent/dsh-native.ts
+++ b/src/agent/dsh-native.ts
@@ -51,7 +51,7 @@ import { APIG_RESIGN_SCHEME, unresolvedRefusals } from "../apig-resign.js";
import { adminRelayEnabled, resolveResignSettings } from "../config.js";
import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, proxyEnvOrigin, singleFlight } from "./native-bootstrap.js";
import { installNativeFetchIntercept, liveStateSlotEffect, noteRoutedOrigin, observeRoutedOrigin, type GateVerdict, type NativeInterceptState } from "./native-intercept.js";
-import { asciiHeaderValue, fetchManifest, fetchProxyVersion, fetchStatus, fetchStatusLatest, forwardTool, reportRuntimeInfo, waitForProxyVersion, type ManifestTool } from "./shared.js";
+import { asciiHeaderValue, fetchManifest, fetchProxyVersion, fetchStatus, fetchStatusLatest, forwardTool, reportAttributionHealth, reportRuntimeInfo, waitForProxyVersion, type ManifestTool } from "./shared.js";
import { createForkAdopter, sideShapedBody } from "./fork-adopt.js";
import { clearIncrementalProbe, INCREMENTAL_TURN_MARKER_HEADER, INCREMENTAL_TURN_ID_HEADER, newIncrementalTurnId, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, sweepStale, type IncrementalWireMessage } from "./incremental-client.js";
import { registerCompactionDisable } from "./dsh-compaction-disable.js";
@@ -1365,6 +1365,37 @@ export function apply(ctx: PluginContext): void {
return url;
}
};
+ // #3581: the refusal evidence above exists ONLY in this host process — the
+ // proxy learns about the silent-direct degradation exclusively through
+ // event reports (first refusal, state change, count doubling, give-up
+ // latch, recovery). Healthy lanes never POST, so the healthy path costs
+ // nothing; a missed report delays visibility, never touches requests.
+ const reportAttrHealth = (): void => {
+ const base = register.base;
+ if (base === undefined) return;
+ void reportAttributionHealth(base, { agent: name, state: attrHealth.state, refusals: attrHealth.refusals, since: attrHealth.since }).catch(() => undefined);
+ };
+ const noteAttrRefusal = (state: "none" | "threw"): void => {
+ if (attrHealth.state === "ok") {
+ attrHealth = { state, refusals: 1, since: Date.now() };
+ attrReportedRefusals = 1;
+ reportAttrHealth();
+ return;
+ }
+ attrHealth.refusals += 1;
+ const changed = attrHealth.state !== state;
+ attrHealth.state = state;
+ if (changed || attrHealth.refusals >= attrReportedRefusals * 2) {
+ attrReportedRefusals = attrHealth.refusals;
+ reportAttrHealth();
+ }
+ };
+ const noteAttrRecovery = (): void => {
+ if (attrHealth.state === "ok") return;
+ attrHealth = { state: "ok", refusals: 0, since: 0 };
+ attrReportedRefusals = 0;
+ reportAttrHealth();
+ };
const refuse = (url: string, attr: GateAttribution): false => {
const key = gateKeyOf(url);
const prev = gateRefusals.get(key);
@@ -1383,6 +1414,7 @@ export function apply(ctx: PluginContext): void {
const line = `bili-native-dsh: model request sent DIRECT (uncompressed) — takeover gate refused ${key}: ${reason} — refusals so far: ${count}${suffix}`;
persistClientEvent(line);
}
+ if (attr.state !== "ok") noteAttrRefusal(attr.state);
return false;
};
// #2924 direction 2: `threw` is an INTERNAL error in the host's
@@ -1394,16 +1426,25 @@ export function apply(ctx: PluginContext): void {
// both ship the full history upstream, which 400s once it exceeds the
// window — all recovery paths vanish the instant the gate lets go).
const settleThrewAttribution = async (url: string, body: { bytes: number } | undefined): Promise => {
- for (let attempt = 1; attempt < threwRetry.attempts; attempt++) {
- await new Promise((resolve) => {
- setTimeout(resolve, threwRetry.delayMs);
- });
- const again = attributionOf(ctx);
- if (again.state === "ok") {
- persistClientEvent(`bili-native-dsh: takeover gate attribution recovered after ${attempt} settle-retr${attempt === 1 ? "y" : "ies"} — ${gateKeyOf(url)} claimed (#2924)`);
- return true;
+ // #3581: after giveUpStreak consecutive requests whose settle-retry
+ // exhausted STILL threw, stop re-settling — a disposed ctx stays
+ // disposed for the host's whole lifetime (#3578), so retrying the same
+ // dead scope per request is pure latency. The gate's single cheap
+ // attributionOf probe per request keeps self-heal alive: the first ok
+ // claim (new agent scope) clears the streak and resumes normal retries.
+ if (threwStreak < threwRetry.giveUpStreak) {
+ for (let attempt = 1; attempt < threwRetry.attempts; attempt++) {
+ await new Promise((resolve) => {
+ setTimeout(resolve, threwRetry.delayMs);
+ });
+ const again = attributionOf(ctx);
+ if (again.state === "ok") {
+ persistClientEvent(`bili-native-dsh: takeover gate attribution recovered after ${attempt} settle-retr${attempt === 1 ? "y" : "ies"} — ${gateKeyOf(url)} claimed (#2924)`);
+ noteAttrRecovery();
+ return true;
+ }
+ if (again.state === "none") return refuse(url, again);
}
- if (again.state === "none") return refuse(url, again);
}
// #2924 direction 1: still `threw` AND the body provably cannot fit —
// fail this one request locally instead of handing upstream a request
@@ -1417,14 +1458,37 @@ export function apply(ctx: PluginContext): void {
if (body !== undefined && window !== undefined && Math.ceil(body.bytes / 4) > window) {
const floorTokens = Math.ceil(body.bytes / 4);
persistClientEvent(`bili-native-dsh: takeover gate refused ${gateKeyOf(url)} LOCALLY (422) — attribution threw and body ≥${floorTokens} tok (floor est ${body.bytes}B/4) exceeds window ${window}; a direct send would 400 upstream (#2924)`);
+ noteAttrRefusal("threw");
return "refuse-oversized";
}
return refuse(url, attributionOf(ctx));
};
state.takeoverGate = (url, body) => {
const attr = attributionOf(ctx);
- if (attr.state === "ok") return true;
- if (attr.state === "threw") return settleThrewAttribution(url, body);
+ if (attr.state === "ok") {
+ threwStreak = 0;
+ threwGiveUpNoticed = false;
+ noteAttrRecovery();
+ return true;
+ }
+ if (attr.state === "threw") {
+ return settleThrewAttribution(url, body).then((verdict) => {
+ if (verdict === true) {
+ threwStreak = 0;
+ threwGiveUpNoticed = false;
+ } else {
+ threwStreak += 1;
+ if (threwStreak >= threwRetry.giveUpStreak && !threwGiveUpNoticed) {
+ threwGiveUpNoticed = true;
+ persistClientEvent(`bili-native-dsh: takeover gate stopped settle-retrying after ${threwStreak} consecutive thrown request(s) — refusing immediately until attribution recovers (restart the host if it stays broken) (#3581)`);
+ reportAttrHealth();
+ }
+ }
+ return verdict;
+ });
+ }
+ threwStreak = 0;
+ threwGiveUpNoticed = false;
return refuse(url, attr);
};
@@ -1930,14 +1994,39 @@ export function _resetWebProfileWarningForTest(): void {
/** #2924 direction 2: a `threw` attribution (host agent scope disposed
* mid-request) gets a bounded settle-retry before the gate decides. The
* defaults cap the added latency of a dying turn at ~(attempts-1)×delayMs;
- * the hook exists so tests exercise the cadence without wall-clock waits
- * (same discipline as BILI_MODEL_INFO_RETRY_MS). */
-let threwRetry = { attempts: 3, delayMs: 250 };
-
-/** Test hook (#2924): override the `threw` settle-retry cadence; no argument
- * restores production defaults. */
-export function _setThrewRetryForTest(cfg?: { attempts: number; delayMs: number }): void {
- threwRetry = cfg ?? { attempts: 3, delayMs: 250 };
+ * #3581 adds giveUpStreak — after that many consecutive requests whose
+ * settle-retry exhausted STILL threw, the gate stops re-settling (a disposed
+ * ctx stays disposed for the host's lifetime, #3578). The hook exists so
+ * tests exercise the cadence without wall-clock waits (same discipline as
+ * BILI_MODEL_INFO_RETRY_MS). */
+const DEFAULT_THREW_RETRY = { attempts: 3, delayMs: 250, giveUpStreak: 3 };
+let threwRetry = { ...DEFAULT_THREW_RETRY };
+
+/** Test hook (#2924/#3581): override the `threw` settle-retry cadence (merge;
+ * missing fields keep production defaults); no argument restores all defaults. */
+export function _setThrewRetryForTest(cfg?: Partial): void {
+ threwRetry = { ...DEFAULT_THREW_RETRY, ...cfg };
+}
+
+// #3581: attribution-health counters backing the /__bili status surface.
+// Module-level like register/webProfileWarned (one live injection per host
+// process); _resetAttributionHealthForTest isolates test scenarios.
+let attrHealth: { state: "ok" | "none" | "threw"; refusals: number; since: number } = { state: "ok", refusals: 0, since: 0 };
+let attrReportedRefusals = 0;
+let threwStreak = 0;
+let threwGiveUpNoticed = false;
+
+/** Test hook (#3581): snapshot the attribution-health counters and give-up latch. */
+export function _attributionHealthForTest(): { state: "ok" | "none" | "threw"; refusals: number; since: number; threwStreak: number; gaveUp: boolean } {
+ return { state: attrHealth.state, refusals: attrHealth.refusals, since: attrHealth.since, threwStreak, gaveUp: threwGiveUpNoticed };
+}
+
+/** Test hook (#3581): reset the attribution-health counters between scenarios. */
+export function _resetAttributionHealthForTest(): void {
+ attrHealth = { state: "ok", refusals: 0, since: 0 };
+ attrReportedRefusals = 0;
+ threwStreak = 0;
+ threwGiveUpNoticed = false;
}
/** Test hook (#2924): seed the model-info cache the gate's oversize arm
diff --git a/src/agent/shared.ts b/src/agent/shared.ts
index 408dea25fd..beec249d4c 100644
--- a/src/agent/shared.ts
+++ b/src/agent/shared.ts
@@ -325,6 +325,31 @@ export async function reportRuntimeInfoOnChange(proxyBase: string | undefined, i
}
}
+type AttributionHealthReport = {
+ agent: string;
+ state: "ok" | "none" | "threw";
+ /** Model requests refused direct in the current degraded episode (0 after recovery). */
+ refusals: number;
+ /** Epoch ms of the first refusal in the current episode (0 while healthy). */
+ since: number;
+};
+
+/** Takeover-attribution health report (#3581): when the host plugin's gate
+ * refuses model traffic (disposed injection after a version swap — #3578),
+ * the proxy must learn about it or the silent-direct degradation stays
+ * invisible in /__bili/status and the panel. Sent ONLY on degradation events
+ * (first refusal, state change, count doubling, give-up latch, recovery) —
+ * fire-and-forget at call sites; a missed report delays visibility, never
+ * touches the request path. */
+export async function reportAttributionHealth(proxyBase: string, health: AttributionHealthReport): Promise {
+ const { ok, status } = await fetchJson(`${proxyBase}/__bili/plugin/attribution`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(health),
+ }, STATUS_TIMEOUT_MS);
+ if (!ok) throw new Error(`attribution report failed (${status})`);
+}
+
/** #2204: business outcome of a forwarded tool call. ok:true means the tool
* RAN; whether it achieved its effect rides the endpoint's machine-readable
* `outcome` field (#1875). `failed` mirrors mcp.ts's mapping so every host
diff --git a/src/plugin.ts b/src/plugin.ts
index 8b9fa0b10c..5ee0f64ce8 100644
--- a/src/plugin.ts
+++ b/src/plugin.ts
@@ -23,6 +23,7 @@ import { log as loggerLog } from "./logger.js";
import { ccrEnabled, ccrLoopConfig, contentStoreOf, retrieveToolName } from "./store.js";
import { emitStreamError, emitUpstreamTruncation } from "./stream-error.js";
import type { TruncationDiag } from "./stream-error.js";
+import { recordAttributionReport } from "./server/attribution-status.js";
/** #2328 Q2: what the pipes know about the upstream HTTP response whose body
* they are piping — threaded in by server.ts so the truncation diag can cite
@@ -619,6 +620,36 @@ export function handlePluginRuntimeInfo(payload: string, res: import("node:http"
res.end(JSON.stringify({ ok: true }));
}
+/** Accept a takeover-attribution health report (#3581). Body:
+ * { agent, state: "ok"|"none"|"threw", refusals, since } — sent by a host
+ * plugin ONLY on degradation events (first refusal, state change, count
+ * doubling, give-up latch, recovery); healthy lanes never POST here, so the
+ * healthy path costs zero round-trips. Latest report wins per agent; the
+ * payload feeds /__bili/status + /__bili/overview (`attribution` field) and
+ * the web panel's takeover-broken banner. */
+export function handlePluginAttribution(payload: string, res: import("node:http").ServerResponse): void {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(payload);
+ } catch {
+ res.writeHead(400, { "content-type": "application/json" });
+ res.end(JSON.stringify({ ok: false, error: "invalid JSON" }));
+ return;
+ }
+ const body = parsed as { agent?: unknown; state?: unknown; refusals?: unknown; since?: unknown };
+ const str = (v: unknown, max: number) => (typeof v === "string" && v.length > 0 && v.length <= max ? v : undefined);
+ const nonNeg = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : undefined);
+ const agent = str(body.agent, 64);
+ if (agent === undefined || (body.state !== "ok" && body.state !== "none" && body.state !== "threw")) {
+ res.writeHead(400, { "content-type": "application/json" });
+ res.end(JSON.stringify({ ok: false, error: "agent and state (ok|none|threw) are required" }));
+ return;
+ }
+ recordAttributionReport(agent, { state: body.state, refusals: nonNeg(body.refusals) ?? 0, since: nonNeg(body.since) ?? 0 });
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ ok: true }));
+}
+
const MAX_PENDING_REGISTERS = 64;
const pendingRegisters: PendingPluginRegister[] = [];
diff --git a/src/server/admin.ts b/src/server/admin.ts
index a8bb50d082..ee372d6048 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 { handlePluginAttribution, handlePluginCompact, 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";
@@ -33,6 +33,7 @@ import { buildSessionReportMd, buildSessionReportSvg } from "../web/report.js";
import { queryLogLines } from "../web/logs-query.js";
import { buildDiagnostics } from "../web/diagnostics.js";
import { storageStatusWire } from "../storage/runtime-status.js";
+import { attributionStatusWire } from "./attribution-status.js";
interface AdminCtx {
opts: ProxyOptions;
@@ -587,6 +588,19 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv
return;
}
}
+ if (req.method === "POST" && req.url === "/__bili/plugin/attribution") {
+ // #3581: event-driven takeover-health report from a host plugin (refusal
+ // transitions only — healthy lanes never hit this route).
+ try {
+ const body = await readBody(req);
+ handlePluginAttribution(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;
+ }
+ }
if (req.method === "POST" && req.url === "/__bili/plugin/compact") {
try {
const body = await readBody(req);
@@ -891,7 +905,7 @@ async function sendStatus(res: http.ServerResponse, opts: ProxyOptions): Promise
loggerLog("warn", `split-session canary (#2170): conversation ${w.base} has live traffic under multiple session keys (design persona forks are excluded): ${w.sessions.map((s) => `${s.id} (requests=${s.requests})`).join("; ")}. For a non-persona host this is the #2165 failure shape (stolen anchor / never-compressing split) — investigate if unexpected.`);
}
}
- res.end(JSON.stringify({ version: VERSION, commit: BUILD_COMMIT, diskVersion, stale, updateReady: updateReadyPayload(), autoRestartOnUpdate: opts.autoRestartOnUpdate, advisory: currentAdvisoryPayload(), pluginAdvisories: detectCostAdvisories(process.env), inFlight: totalInFlight(), splitSessions: splitWarnings, conflicts: summarizeConflicts(listSessions()), storage: storageStatusWire() }, null, 2));
+ res.end(JSON.stringify({ version: VERSION, commit: BUILD_COMMIT, diskVersion, stale, updateReady: updateReadyPayload(), autoRestartOnUpdate: opts.autoRestartOnUpdate, advisory: currentAdvisoryPayload(), pluginAdvisories: detectCostAdvisories(process.env), inFlight: totalInFlight(), splitSessions: splitWarnings, conflicts: summarizeConflicts(listSessions()), storage: storageStatusWire(), attribution: attributionStatusWire() }, null, 2));
}
// #2090 plan A — read-only view backing the web UI's "Signed upstreams" card:
@@ -950,6 +964,7 @@ async function sendOverview(res: http.ServerResponse, opts: ProxyOptions): Promi
passthrough: { enabled: !!opts.passthrough, source: opts.passthroughSource },
alerts: getUpstreamAlerts(),
storage: storageStatusWire(),
+ attribution: attributionStatusWire(),
}, null, 2));
}
diff --git a/src/server/attribution-status.ts b/src/server/attribution-status.ts
new file mode 100644
index 0000000000..32b6bcb46e
--- /dev/null
+++ b/src/server/attribution-status.ts
@@ -0,0 +1,40 @@
+// #3581: takeover-failure visibility. When a host plugin's attribution gate
+// refuses model traffic (injected code disposed after a version swap — #3578),
+// every request silently goes DIRECT: no compression, no session registration,
+// tools 404. The refusal evidence lives in the HOST process; the proxy only
+// learns about it when a plugin reports it (fire-and-forget POST on refusal
+// events — healthy paths report nothing). This module keeps the LATEST report
+// per agent in memory and feeds both status surfaces (#2152 parity: one
+// wire helper for /__bili/status AND /__bili/overview) so the web panel can
+// replace the misleading "0 running" with an explicit "takeover broken" banner.
+type AttributionState = "ok" | "none" | "threw";
+
+interface AttributionReport {
+ state: AttributionState;
+ /** Model requests refused direct in the current degraded episode (resets to 0 on recovery). */
+ refusals: number;
+ /** Epoch ms of the first refusal in the current episode; 0 while healthy. */
+ since: number;
+}
+
+const reports = new Map();
+
+/** Record seam: latest-report-wins per agent. Called from the
+ * /__bili/plugin/attribution endpoint after validation. */
+export function recordAttributionReport(agent: string, report: AttributionReport): void {
+ reports.set(agent, { state: report.state, refusals: report.refusals, since: report.since });
+}
+
+/** Wire payload shared by /__bili/status and /__bili/overview (#2152 parity).
+ * Empty object until the first report arrives — a healthy lane never reports,
+ * so absence means "no degradation observed", not "no plugins". */
+export function attributionStatusWire(): Record {
+ const out: Record = {};
+ for (const [agent, r] of reports) out[agent] = { state: r.state, refusals: r.refusals, since: r.since };
+ return out;
+}
+
+/** Test hook: clear all reported agents between scenarios. */
+export function _resetAttributionStatusForTest(): void {
+ reports.clear();
+}
diff --git a/src/web/client.ts b/src/web/client.ts
index dfce0e086b..65c2f14a7c 100644
--- a/src/web/client.ts
+++ b/src/web/client.ts
@@ -581,6 +581,32 @@ export const WEB_CLIENT = `(function () {
stale.classList.remove("show");
stale.innerHTML = "";
}
+ // #3581: takeover-broken notice — a plugin host reports its attribution
+ // gate degradation event-driven (first refusal / state change / give-up
+ // latch / recovery), and the proxy keeps the latest per agent. Shown
+ // only when traffic is actually going direct: at least one agent is
+ // degraded AND no session is live (live > 0 means compression is still
+ // serving this host, so the bare "0 running" sub-line is not misleading).
+ const attEl = $("attribution-banner");
+ if (attEl) {
+ const att = d.attribution;
+ const degraded = att && typeof att === "object"
+ ? Object.entries(att).filter(([, a]) => a && typeof a === "object" && a.state !== "ok" && (a.refusals || 0) > 0)
+ : [];
+ // #3581: only meaningful while nothing runs — with live sessions the
+ // takeover is demonstrably working for them.
+ const show = degraded.length > 0 && ((d.overview || {}).live || 0) === 0;
+ if (show) {
+ const [agent, entry] = degraded[0];
+ attEl.hidden = false;
+ attEl.classList.add("show");
+ attEl.innerHTML = "" + escapeHtml(t("sys.attribution_broken", { agent: agent, n: entry.refusals })) + "";
+ } else {
+ attEl.hidden = true;
+ attEl.classList.remove("show");
+ attEl.innerHTML = "";
+ }
+ }
const sb = $("storage-degraded-banner");
if (sb) {
const sg = d.storage;
diff --git a/src/web/i18n.ts b/src/web/i18n.ts
index dee2ee9f16..e93a6b6776 100644
--- a/src/web/i18n.ts
+++ b/src/web/i18n.ts
@@ -103,9 +103,10 @@ export const MESSAGES: Record> = {
"sys.update": "升级提醒:",
"sys.update_available": "发现 critical 修复,请升级到 v{version} 或更新版本 — {summary}",
"sys.update_ready": "critical 修复已就绪 v{version} — 重启 bili 即可生效",
- "sys.stale": "磁盘已有新版本 v{disk} —— 重启 bili 生效(当前运行 v{running})",
+ "sys.stale": "磁盘已有新版本 v{disk} —— 当前运行 v{running},重启宿主后新代码才生效",
"sys.stale_auto": "自动重启已启用,空闲时自动切换",
"sys.stale_manual": "自动重启未启用(需要 --auto-restart-on-update)",
+ "sys.attribution_broken": "接管已失效({agent}):模型请求正在直连(不压缩),已拒 {n} 次 — 重启宿主可恢复",
"sys.pt_on": "Passthrough 已开启:所有请求原样转发,压缩关闭。来源:",
"sys.pt_env": "ACP_PASSTHROUGH 环境变量(或 --passthrough 参数)",
"sys.pt_file": "配置文件 passthrough: true",
@@ -582,9 +583,10 @@ export const MESSAGES: Record> = {
"sys.update": "Update notice:",
"sys.update_available": "critical fix available — upgrade to v{version} or newer: {summary}",
"sys.update_ready": "critical fix ready (v{version}) — restart bili to apply",
- "sys.stale": "Newer version v{disk} on disk — restart bili to apply (running v{running})",
+ "sys.stale": "Newer version v{disk} on disk — running v{running}; restart the host to load the new code",
"sys.stale_auto": "Auto-restart enabled — switches automatically when idle",
"sys.stale_manual": "Auto-restart not enabled (needs --auto-restart-on-update)",
+ "sys.attribution_broken": "Takeover broken ({agent}): model requests are going direct (uncompressed), {n} refused — restart the host to restore compression",
"sys.pt_on": "Passthrough ON: all requests forwarded as-is, compression disabled. Source:",
"sys.pt_env": "ACP_PASSTHROUGH env var (or --passthrough flag)",
"sys.pt_file": "config file passthrough: true",
diff --git a/src/web/page.ts b/src/web/page.ts
index aa75a8dbb7..f73e4bbac2 100644
--- a/src/web/page.ts
+++ b/src/web/page.ts
@@ -23,6 +23,7 @@ export function renderPage(origin: string, version: string, embed = false, theme
+
diff --git a/tests/dsh-native.test.ts b/tests/dsh-native.test.ts
index 293b6af152..edc01d5a86 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, _resetRegisterForTest, _setModelInfoForTest, _setSpawnForTest, _setThrewRetryForTest, _settleNativeForTest, _stateHeadersForTest, _stateRespawnForTest, _stateTakeoverGateForTest, _stateToolsReadyForTest, _stateBeforeSendForTest, _stateOnResponseForTest, _noteRoutedForTest, _resetRoutedForTest, _resetWebProfileWarningForTest, _resetTitlesForTest, type PluginContext } from "../src/agent/dsh-native.ts";
+import { apply, planNativeDsh, shouldBootstrapNativeDsh, persistClientEvent, _attributionHealthForTest, _resetAttributionHealthForTest, _resetRegisterForTest, _setModelInfoForTest, _setSpawnForTest, _setThrewRetryForTest, _settleNativeForTest, _stateHeadersForTest, _stateRespawnForTest, _stateTakeoverGateForTest, _stateToolsReadyForTest, _stateBeforeSendForTest, _stateOnResponseForTest, _noteRoutedForTest, _resetRoutedForTest, _resetWebProfileWarningForTest, _resetTitlesForTest, type PluginContext } from "../src/agent/dsh-native.ts";
import { __resetIncrementalClientForTests } from "../src/agent/incremental-client.ts";
import { BILI_COMPACTION_DISABLE_SERVICE } from "../src/agent/dsh-compaction-disable.ts";
@@ -423,7 +423,9 @@ type MockTool = { name: string; description?: string; inputSchema: unknown };
type NameCall = { conversationId: string; name: string };
-function mockBiliHandler(toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>, statusResponder?: (url: string) => unknown | undefined, nameCalls?: NameCall[], nameStatus?: number, turnEnabled?: boolean): (req: http.IncomingMessage, res: http.ServerResponse) => void {
+type MockAttributionCall = { agent: string; state: string; refusals: number; since: number };
+
+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[]): (req: http.IncomingMessage, res: http.ServerResponse) => void {
const manifestTools: MockTool[] = [
{
name: "compress",
@@ -480,13 +482,33 @@ function mockBiliHandler(toolCalls: Array<{ conversationId: string; tool: string
res.end(JSON.stringify(body));
return;
}
+ // #3581: plugin→proxy attribution-health reports — captured for the
+ // event-driven visibility tests (first refusal / state change / recovery).
+ if (url === "/__bili/plugin/attribution") {
+ let body = "";
+ req.on("data", (c) => (body += c));
+ req.on("end", () => {
+ if (attributionCalls !== undefined) {
+ const parsed = JSON.parse(body) as Record;
+ attributionCalls.push({
+ agent: typeof parsed.agent === "string" ? parsed.agent : "",
+ state: typeof parsed.state === "string" ? parsed.state : "",
+ refusals: typeof parsed.refusals === "number" ? parsed.refusals : -1,
+ since: typeof parsed.since === "number" ? parsed.since : -1,
+ });
+ }
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
res.writeHead(404);
res.end("{}");
};
}
-function startMockProxy(toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>, statusResponder?: (url: string) => unknown | undefined, nameCalls?: NameCall[], nameStatus?: number, turnEnabled?: boolean): Promise<{ origin: string; close: () => void }> {
- const server = http.createServer(mockBiliHandler(toolCalls, statusResponder, nameCalls, nameStatus, turnEnabled));
+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[]): Promise<{ origin: string; close: () => void }> {
+ const server = http.createServer(mockBiliHandler(toolCalls, statusResponder, nameCalls, nameStatus, turnEnabled, attributionCalls));
return new Promise((resolve) => {
server.listen(0, "127.0.0.1", () => {
const addr = server.address() as { port: number };
@@ -1875,6 +1897,126 @@ test("#2924 gate `threw` persists: provably-oversized body refuses LOCALLY, ever
}
});
+test("#3581 gate degradation reports event-driven; give-up latch stops pointless settle-retries on a dead scope", async () => {
+ const attrCalls: MockAttributionCall[] = [];
+ const proxy = await startMockProxy([], undefined, undefined, undefined, false, attrCalls);
+ const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-3581a-state-"));
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-3581a-home-"));
+ try {
+ await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin, XDG_STATE_HOME: stateHome }, async () => {
+ _resetRegisterForTest(proxy.origin);
+ _resetAttributionHealthForTest();
+ const ctx = mockCtx();
+ apply(ctx);
+ await waitFor(() => ctx.registeredTools.length === 1, "initial attach tool registration");
+ const gate = _stateTakeoverGateForTest();
+ assert.ok(gate !== undefined, "takeoverGate installed");
+ // giveUpStreak stays at its production default (3); fast cadence for the suite.
+ _setThrewRetryForTest({ attempts: 2, delayMs: 1 });
+ let probes = 0;
+ ctx.agents.currentInitiator = () => {
+ probes += 1;
+ throw new Error("agent initiator scope is disposed");
+ };
+ const url = "https://api.gate-3581a.test/v1/chat/completions";
+ const logFile = path.join(stateHome, "billion-context", "bili.log");
+ // #3578 shape: the ALS boundary throws for the host's whole lifetime.
+ // Per-request probe cost while settling (attempts: 2): the gate's
+ // initial attributionOf, the one settle-retry, the oversize arm's
+ // window resolution (sessionModelTargetOf), and the final
+ // refuse(attributionOf) re-probe → 4. The latch removes exactly the
+ // settle-retry probe → 3.
+ assert.equal(await gate(url), false);
+ assert.equal(probes, 4, "request 1: four probes while settling");
+ assert.equal(await gate(url), false);
+ assert.equal(probes, 8, "request 2: still settling");
+ assert.equal(await gate(url), false);
+ assert.equal(probes, 12, "request 3: streak reaches giveUpStreak → latch arms");
+ assert.equal(await gate(url), false);
+ assert.equal(probes, 15, "request 4: latch skips the settle loop — one fewer probe");
+ assert.equal(await gate(url), false);
+ assert.equal(probes, 18, "request 5: reduced cost holds");
+ const health = _attributionHealthForTest();
+ assert.equal(health.state, "threw");
+ assert.equal(health.refusals, 5);
+ assert.ok(health.since > 0, "episode start timestamp recorded");
+ assert.equal(health.threwStreak, 5);
+ assert.equal(health.gaveUp, true);
+ // event-driven reporting: first refusal, doubling (2), latch (3) — no per-request flood
+ await waitFor(() => attrCalls.length >= 3, "attribution health reports");
+ assert.ok(attrCalls.every((c) => c.agent === "bili-native"), "reports carry the agent name");
+ assert.deepEqual({ state: attrCalls[0]!.state, refusals: attrCalls[0]!.refusals }, { state: "threw", refusals: 1 });
+ assert.ok(attrCalls[0]!.since > 0);
+ assert.equal(attrCalls[1]!.refusals, 2, "doubling report");
+ assert.ok(attrCalls[attrCalls.length - 1]!.refusals >= 3, "latch carries the latest count");
+ const content = fs.readFileSync(logFile, "utf8");
+ assert.match(content, /stopped settle-retrying after 3 consecutive thrown request\(s\)/);
+ });
+ } finally {
+ _setThrewRetryForTest();
+ proxy.close();
+ rmrf(stateHome);
+ rmrf(home);
+ _resetRegisterForTest(undefined);
+ _resetAttributionHealthForTest();
+ }
+});
+
+test("#3581 recovery clears the episode, re-arms settle-retry, and reports ok", async () => {
+ const attrCalls: MockAttributionCall[] = [];
+ const proxy = await startMockProxy([], undefined, undefined, undefined, false, attrCalls);
+ const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-3581b-state-"));
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-3581b-home-"));
+ try {
+ await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin, XDG_STATE_HOME: stateHome }, async () => {
+ _resetRegisterForTest(proxy.origin);
+ _resetAttributionHealthForTest();
+ const ctx = mockCtx();
+ apply(ctx);
+ await waitFor(() => ctx.registeredTools.length === 1, "initial attach tool registration");
+ const gate = _stateTakeoverGateForTest();
+ assert.ok(gate !== undefined, "takeoverGate installed");
+ _setThrewRetryForTest({ attempts: 2, delayMs: 1 });
+ let probes = 0;
+ ctx.agents.currentInitiator = () => {
+ probes += 1;
+ throw new Error("agent initiator scope is disposed");
+ };
+ const url = "https://api.gate-3581b.test/v1/chat/completions";
+ for (let i = 0; i < 3; i++) assert.equal(await gate(url), false);
+ assert.equal(_attributionHealthForTest().gaveUp, true, "latch armed by three exhausted throws");
+ // a new agent scope lands (host re-created it): the first ok claim heals.
+ ctx.agents.currentInitiator = () => ({ session: { id: "s3581b" } });
+ assert.equal(await gate(url), true, "recovered attribution claims immediately");
+ const healed = _attributionHealthForTest();
+ assert.deepEqual({ state: healed.state, refusals: healed.refusals, since: healed.since }, { state: "ok", refusals: 0, since: 0 });
+ assert.equal(healed.threwStreak, 0);
+ assert.equal(healed.gaveUp, false);
+ await waitFor(() => attrCalls.some((c) => c.state === "ok"), "recovery report");
+ const okCall = attrCalls.filter((c) => c.state === "ok").pop()!;
+ assert.equal(okCall.refusals, 0);
+ // break again: settle-retry is RE-ARMED (the latch followed the episode, not the process).
+ let probes2 = 0;
+ ctx.agents.currentInitiator = () => {
+ probes2 += 1;
+ throw new Error("agent initiator scope is disposed again");
+ };
+ assert.equal(await gate(url), false);
+ assert.equal(probes2, 4, "settle-retry active again after recovery (full 4-probe cost)");
+ const reBroken = _attributionHealthForTest();
+ assert.equal(reBroken.state, "threw");
+ assert.equal(reBroken.refusals, 1, "fresh episode starts at one refusal");
+ });
+ } finally {
+ _setThrewRetryForTest();
+ proxy.close();
+ rmrf(stateHome);
+ rmrf(home);
+ _resetRegisterForTest(undefined);
+ _resetAttributionHealthForTest();
+ }
+});
+
test("#1158 apply() persists bootstrap failures to bili.log (GUI stderr is invisible)", async () => {
const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-1158c-state-"));
const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-1158c-home-"));
diff --git a/tests/issue3581-attribution-health.test.ts b/tests/issue3581-attribution-health.test.ts
new file mode 100644
index 0000000000..041763630a
--- /dev/null
+++ b/tests/issue3581-attribution-health.test.ts
@@ -0,0 +1,177 @@
+// #3581: when a plugin host's takeover gate degrades at runtime (disposed
+// agent scope, disabled plugin), model traffic silently goes direct
+// uncompressed until a host restart. The plugin reports its attribution
+// health event-driven to POST /__bili/plugin/attribution; the proxy keeps
+// the latest per agent and exposes it on BOTH status surfaces (#2152 parity)
+// so the panel can show an explicit "takeover broken" notice instead of a
+// bare "0 running". These tests pin the wire contract:
+// 1. default is {} (no report yet) on both surfaces — identical payload;
+// 2. a valid report lands per-agent and is byte-identical on
+// /__bili/status and /__bili/overview (one shared wire helper);
+// 3. malformed reports are rejected loudly (400), never merged into
+// defaults or dropped fields (#155 discipline);
+// 4. the page ships the banner element and the client references it plus
+// the localized copy key.
+import test from "node:test";
+import assert from "node:assert/strict";
+import http from "node:http";
+import { once } from "node:events";
+import { mkdtempSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { defaultConfig } from "acp-kernel";
+import { startServer } from "../src/server.ts";
+import type { ProxyOptions } from "../src/config.ts";
+import { _resetAttributionStatusForTest } from "../src/server/attribution-status.ts";
+import { renderPage } from "../src/web/page.ts";
+import { WEB_CLIENT } from "../src/web/client.ts";
+import { VERSION } from "../src/version.ts";
+import { rmrf } from "./tmp-rm.ts";
+
+process.env.BILI_PERSIST_ZSTD = "0";
+
+const ENV_KEYS = ["BILI_SESSIONS_DIR", "BILI_CONFIG_FILE", "XDG_CACHE_HOME", "XDG_STATE_HOME"] as const;
+type EnvSnap = Partial>;
+
+function saveEnv(): EnvSnap {
+ const snap: EnvSnap = {};
+ for (const k of ENV_KEYS) snap[k] = process.env[k];
+ return snap;
+}
+
+function restoreEnv(snap: EnvSnap): void {
+ for (const k of ENV_KEYS) {
+ if (snap[k] === undefined) delete process.env[k];
+ else process.env[k] = snap[k];
+ }
+}
+
+function isolate(base: string): void {
+ mkdirSync(path.join(base, "sessions"), { recursive: true });
+ process.env.BILI_SESSIONS_DIR = path.join(base, "sessions");
+ process.env.BILI_CONFIG_FILE = path.join(base, "absent-config.json");
+ process.env.XDG_CACHE_HOME = path.join(base, "cache");
+ process.env.XDG_STATE_HOME = path.join(base, "state");
+}
+
+function close(server: http.Server): Promise {
+ return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
+}
+
+async function freePort(): Promise {
+ const server = http.createServer();
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ const port = (server.address() as { port: number }).port;
+ await close(server);
+ return port;
+}
+
+interface AttributionWireEntry {
+ state: "ok" | "none" | "threw";
+ refusals: number;
+ since: number;
+}
+
+function makeOpts(upstreamPort: number): ProxyOptions {
+ return {
+ port: 0,
+ host: "127.0.0.1",
+ upstream: `http://127.0.0.1:${upstreamPort}`,
+ routes: {},
+ modelContextLimit: 400_000,
+ kernelConfig: defaultConfig(400_000),
+ compress: { injectTool: false, 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: [] },
+ };
+}
+
+test("#3581 attribution health: report lands per-agent, status/overview parity, malformed rejected, page ships the banner", async () => {
+ const snap = saveEnv();
+ const base = mkdtempSync(path.join(tmpdir(), "bili-attribution-health-"));
+ let proxy: http.Server | undefined;
+ try {
+ isolate(base);
+ _resetAttributionStatusForTest();
+ const upstreamPort = await freePort();
+ proxy = await startServer(makeOpts(upstreamPort));
+ await once(proxy, "listening");
+ const port = (proxy.address() as { port: number }).port;
+ const url = (p: string) => `http://127.0.0.1:${port}${p}`;
+
+ // 1. default: nothing reported yet — both surfaces carry {} identically
+ let s = await (await fetch(url("/__bili/status"))).json() as { attribution: Record };
+ let o = await (await fetch(url("/__bili/overview"))).json() as { attribution: Record };
+ assert.deepEqual(s.attribution, {}, "status starts empty");
+ assert.deepEqual(o.attribution, {}, "overview starts empty");
+ assert.deepEqual(o.attribution, s.attribution, "empty-state parity");
+
+ // 2. valid report: per-agent entry (the agent name IS the map key),
+ // byte-identical on both surfaces
+ const post = (body: unknown) => fetch(url("/__bili/plugin/attribution"), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+ const thrown = { state: "threw", refusals: 7, since: 1760000000000 };
+ let res = await post({ agent: "dsh", ...thrown });
+ assert.equal(res.status, 200, "valid report accepted");
+ assert.deepEqual(await res.json(), { ok: true });
+ s = await (await fetch(url("/__bili/status"))).json() as { attribution: Record };
+ o = await (await fetch(url("/__bili/overview"))).json() as { attribution: Record };
+ assert.deepEqual(s.attribution.dsh, thrown, "status carries the report verbatim under its agent key");
+ assert.deepEqual(o.attribution, s.attribution, "status/overview attribution parity (one shared helper)");
+
+ // second agent coexists; re-reporting one agent is latest-wins
+ const none = { state: "none", refusals: 1, since: 1760000001000 };
+ res = await post({ agent: "opencode", ...none });
+ assert.equal(res.status, 200);
+ s = await (await fetch(url("/__bili/status"))).json() as { attribution: Record };
+ assert.deepEqual(s.attribution.opencode, none, "per-agent keys stay independent");
+ assert.equal(s.attribution.dsh.refusals, 7, "other agents untouched");
+ const updated = { state: "ok", refusals: 0, since: 0 };
+ res = await post({ agent: "dsh", ...updated });
+ assert.equal(res.status, 200);
+ s = await (await fetch(url("/__bili/status"))).json() as { attribution: Record };
+ assert.deepEqual(s.attribution.dsh, updated, "recovery report replaces the degraded episode");
+
+ // 3. malformed reports rejected loudly — never merged into defaults
+ for (const bad of [
+ { agent: "dsh", state: "exploded", refusals: 1, since: 1 }, // bad state
+ { state: "threw", refusals: 1, since: 1 }, // missing agent
+ { agent: "", state: "threw", refusals: 1, since: 1 }, // empty agent
+ ]) {
+ const r = await post(bad);
+ assert.equal(r.status, 400, `malformed report rejected: ${JSON.stringify(bad)}`);
+ assert.deepEqual(await r.json(), { ok: false, error: "agent and state (ok|none|threw) are required" });
+ }
+ res = await post({ agent: "pi", state: "none" });
+ assert.equal(res.status, 200, "missing refusals/since default to 0");
+ s = await (await fetch(url("/__bili/status"))).json() as { attribution: Record };
+ assert.deepEqual(s.attribution.pi, { state: "none", refusals: 0, since: 0 }, "numeric fields default to 0");
+ res = await fetch(url("/__bili/plugin/attribution"), { method: "POST", headers: { "content-type": "application/json" }, body: "{not json" });
+ assert.equal(res.status, 400, "non-JSON body rejected");
+ assert.deepEqual(await res.json(), { ok: false, error: "invalid JSON" });
+
+ // 4. web surface ships the banner element + localized copy
+ const html = renderPage(`http://127.0.0.1:${port}`, VERSION);
+ assert.ok(html.includes('id="attribution-banner"'), "page carries the banner div");
+ assert.ok(WEB_CLIENT.includes('"attribution-banner"'), "client targets the banner element");
+ assert.ok(WEB_CLIENT.includes('t("sys.attribution_broken"'), "client composes the localized notice");
+ assert.ok(WEB_CLIENT.includes("escapeHtml(t(\"sys.attribution_broken\""), "agent name/count are HTML-escaped before innerHTML");
+ } finally {
+ if (proxy) await close(proxy);
+ _resetAttributionStatusForTest();
+ restoreEnv(snap);
+ rmrf(base);
+ }
+});