Skip to content
Merged
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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<acp tokens="2" type="text">m00001</acp>` (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.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
129 changes: 109 additions & 20 deletions src/agent/dsh-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
Expand All @@ -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
Expand All @@ -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<GateVerdict> => {
for (let attempt = 1; attempt < threwRetry.attempts; attempt++) {
await new Promise<void>((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<void>((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
Expand All @@ -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);
};

Expand Down Expand Up @@ -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<typeof DEFAULT_THREW_RETRY>): 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
Expand Down
25 changes: 25 additions & 0 deletions src/agent/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
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
Expand Down
Loading
Loading