Skip to content
2 changes: 1 addition & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,7 @@ export async function main(): Promise<void> {
packageName: PACKAGE_NAME,
resolveProxy: updaterResolveProxy,
updateTag,
globalCheck: () => checkForUpdate({ packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true, resolveProxy: updaterResolveProxy, updateTag }, true),
globalCheck: async () => { await checkForUpdate({ packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true, resolveProxy: updaterResolveProxy, updateTag }, true); },
log: (_level, msg) => console.log(msg),
});
for (const line of lines) console.log(line);
Expand Down
114 changes: 114 additions & 0 deletions src/client-ua-registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// #4649: recently observed client user-agents, per client family. The
// diagnostics blob used to carry ONLY dsh profile-bundle versions, so a
// conflict report from a non-dsh client (e.g. codex, #4648) had neither the
// client's own version nor — before the codex entries in CONFLICT_LOG_PATTERNS
// landed — any log evidence to adjudicate with, forcing a manual round-trip
// for `codex --version` and hand-picked log lines.
//
// The proxy sees the requesting UA on every model request; this module keeps
// a bounded in-memory map of what was observed and the "host client versions"
// section of the report publishes it. Process-scoped by design: a restart
// starts fresh, and a report generated while traffic flows reflects live
// clients. In-memory only — nothing here is persisted or sent upstream.
//
// Publish discipline: the values are raw client-supplied header bytes, but
// they only leave the process through buildDiagnostics' sink-level
// redactForPublish (#4427), which scrubs credential shapes, masks private
// hosts, and ~-normalizes home paths across the whole blob. Length is bounded
// at ingest (UA_MAX_CHARS) so one hostile UA cannot bloat the pasteable blob.

import { isCodexClient } from "./codex-compact.js";
import { sniffScanClient } from "./thirdparty-scan.js";

// Read directly (wire literal) instead of via plugin.ts — same discipline as
// codex-compact.ts / session-id.ts: importing plugin.ts back into the request
// path would close an ESM cycle through loop/tag-echo-filter.ts.
const BILI_PLUGIN_MARKER = "x-bili-plugin";

const FAMILY_CAP = 24;
const UA_CAP_PER_FAMILY = 8;
const UA_MAX_CHARS = 120;
const OTHER_FAMILY = "other";

interface FamilyEntry {
uas: Map<string, number>;
}

const families = new Map<string, FamilyEntry>();

function headerString(headers: Record<string, string | string[] | undefined>, name: string): string | undefined {
const v = headers[name];
if (Array.isArray(v)) return typeof v[0] === "string" ? v[0] : undefined;
return typeof v === "string" ? v : undefined;
}

/** Client family for UA bookkeeping — mirrors conflictClientOf's resolution
* ladder (declared plugin agent > header sniff > codex UA shape) keyed off
* the raw request headers. "mcp" is not a client name (MCP evidence flip,
* #760b), so it falls through like in conflict-watch. */
export function clientFamilyOf(headers: Record<string, string | string[] | undefined>): string {
const agent = headerString(headers, BILI_PLUGIN_MARKER);
if (agent && agent !== "mcp") return agent;
const sniffed = sniffScanClient(headers);
if (sniffed) return sniffed;
const ua = headerString(headers, "user-agent");
if (ua && isCodexClient({ "user-agent": ua })) return "codex";
return OTHER_FAMILY;
}

/** Latest-wins per exact UA string; evicts the oldest UA inside a family past
* UA_CAP_PER_FAMILY, and the least-recently-seen family past FAMILY_CAP, so a
* hostile or churning client can only occupy bounded slots. */
export function recordClientUa(headers: Record<string, string | string[] | undefined>): void {
const raw = headerString(headers, "user-agent");
if (!raw || !raw.trim()) return;
const ua = raw.trim().slice(0, UA_MAX_CHARS);
const now = Date.now();
let fam = families.get(clientFamilyOf(headers));
if (!fam) {
if (families.size >= FAMILY_CAP) {
let oldestKey: string | undefined;
let oldestAt = Infinity;
for (const [k, v] of families) {
let newest = -Infinity;
for (const t of v.uas.values()) if (t > newest) newest = t;
if (newest < oldestAt) { oldestAt = newest; oldestKey = k; }
}
if (oldestKey !== undefined) families.delete(oldestKey);
}
fam = { uas: new Map() };
families.set(clientFamilyOf(headers), fam);
}
fam.uas.set(ua, now);
while (fam.uas.size > UA_CAP_PER_FAMILY) {
let oldestUa: string | undefined;
let oldestAt = Infinity;
for (const [u, t] of fam.uas) {
// strict < keeps first-inserted on timestamp ties (FIFO eviction)
if (t < oldestAt) { oldestAt = t; oldestUa = u; }
}
if (oldestUa === undefined) break;
fam.uas.delete(oldestUa);
}
}

interface ObservedUa {
family: string;
ua: string;
}

/** All recorded observations — families alphabetical, newest-first within a
* family — for the diagnostics section to render under its own display cap. */
export function recentClientUas(): ObservedUa[] {
const out: ObservedUa[] = [];
const sortedFamilies = [...families.entries()].sort((a, b) => a[0].localeCompare(b[0]));
for (const [family, fam] of sortedFamilies) {
const sortedUas = [...fam.uas.entries()].sort((a, b) => b[1] - a[1]);
for (const [ua] of sortedUas) out.push({ family, ua });
}
return out;
}

export function _resetClientUaRegistryForTest(): void {
families.clear();
}
10 changes: 6 additions & 4 deletions src/server/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -976,10 +976,12 @@ function handleConflictsClear(url: string, res: http.ServerResponse, log: (level

// ---- #3719: web 更新/Updates tab actions ---------------------------------

/** POST /__bili/update/check — force one registry check through the shared
* update options (same lock/throttle/proxy gates as the background loop).
* Always HTTP 200: an unwired process answers {ok:false, error} so the panel
* can show the string verbatim instead of failing the fetch. */
/** POST /__bili/update/check — run ONE check-only registry pass through the
* shared update options (#4791): full gate ladder, structured verdict
* ({status, latest?, candidate?, note?}), NO download/install — installs
* happen on /__bili/update/install. Always HTTP 200: an unwired process
* answers {ok:false, error} so the panel can show the string verbatim
* instead of failing the fetch. */
async function handleUpdateCheck(res: http.ServerResponse): Promise<void> {
if (!updateActionsAvailable()) {
res.writeHead(200, { "content-type": "application/json" });
Expand Down
7 changes: 7 additions & 0 deletions src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { FALLBACK_EFFECTIVE_WINDOW_FLOOR, findRoute, findRouteKey, lookupContext
import { resolveProxyDecision } from "../upstream-proxy.js";
import { contextFromRegistry, peekRegistryContext, peekRegistryOutputLimit, peekRegistryPriceProfile } from "../registry.js";
import { stampBillingPrice } from "../billing.js";
import { recordClientUa } from "../client-ua-registry.js";
import { codexAlignedWindow } from "../codex-models.js";
import { DecodedRequestAdmission, DecodedRequestBusyError } from "../request-body-budget.js";
import { hostIdForLog, maskHeadersForLog, maskUrlForLog, maskUrlsInText } from "../log-mask.js";
Expand Down Expand Up @@ -1673,6 +1674,12 @@ async function handleRequest(
}
if (!pluginAgent && typeof session.metadata.pluginAgent === "string") pluginAgent = session.metadata.pluginAgent;
if (pluginAgent && !pluginConversation) pluginConversation = conversation;
// #4649: remember this request's client UA in the bounded registry so a
// diagnostics report carries the client's own version (non-dsh lanes
// have no profile bundle to read it from). Runs for EVERY model
// request — unlike the clientHint block below, which only fills the
// session's first-seen hint.
recordClientUa(req.headers);
// #1426 web UI: persist which client this session came from, first hit wins.
// Plugin agents are already recorded above as metadata.pluginAgent; non-plugin
// clients fall back to header sniffing, then to a truncated User-Agent hint.
Expand Down
32 changes: 20 additions & 12 deletions src/server/update-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@
* the updater, it only holds THIS process's UpdateOptions (registered once by
* the CLI alongside startAutoUpdate — the SAME object the background loop
* runs on) and exposes guarded actions on top of its existing exports:
* - a forced registry check → checkForUpdate(opts, true)
* - a pinned-version install → forceInstallVersion(v, dir, opts, "web-panel")
* - a check-only registry pass → checkForUpdate(opts, false, true) (#4791):
* full gate ladder, structured verdict, NO download/install
* - a pinned-version install → forceInstallVersion(v, dir, opts, "web-panel", "manual-web")
* (upgrade to a newer release OR rollback to an older one)
* Each action carries one in-process dedupe flag so the panel cannot stack
* concurrent runs — a second concurrent caller gets {ok:true, already:true}
* instead of a duplicate registry/install storm. An unregistered process
* (autoUpdate off, embedded use, tests) degrades to plain error strings;
* nothing here throws into the HTTP handlers.
*/
import { checkForUpdate, findInstallDir, forceInstallVersion, lastUpdateCheckTime, readDiskVersion, staleInstallStatus, type UpdateOptions } from "../update.js";
import { checkForUpdate, findInstallDir, forceInstallVersion, lastUpdateCheckTime, readDiskVersion, staleInstallStatus, type UpdateCheckOutcome, type UpdateOptions } from "../update.js";
import { getUpdateVisibility } from "../update-notes.js";
import { log as loggerLog } from "../logger.js";

Expand Down Expand Up @@ -67,19 +68,26 @@ function looksLikeSemver(v: string): boolean {
return /^v?[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(v);
}

/** Force ONE registry check through the shared update options — same lock,
* throttle and proxy gates as the background loop (force=true skips the
* throttle window and advisory deferrals by design). A concurrent second
* call reports {ok:true, already:true}; network failures come back as
* {ok:false, error} — never a throw. */
export async function triggerManualCheck(): Promise<{ ok: boolean; error?: string; already?: boolean }> {
/** Run ONE check-only registry pass through the shared update options
* (#4791): the full gate ladder runs with every safety gate armed — advisory
* block/deferral, source-checkout guard, single-writer guard, remote policy —
* but nothing downloads or installs. force stays FALSE so a gate reports its
* verdict instead of being bypassed; only the pacing gates (throttle window,
* install-failure backoff) are skipped, and the last-checked marker still
* refreshes. The structured verdict ({status, latest?, candidate?, note?}) is
* passed through for the panel; installs happen on /__bili/update/install.
* A concurrent second call reports {ok:true, already:true}; failures come
* back as {ok:false, error} — never a throw. */
export async function triggerManualCheck(): Promise<{ ok: boolean; error?: string; already?: boolean; status?: UpdateCheckOutcome["status"]; latest?: string; candidate?: string; note?: string }> {
const opts = registeredOpts;
if (opts === undefined) return { ok: false, error: "self-update not wired in this process" };
if (checking) return { ok: true, already: true };
checking = true;
try {
await checkForUpdate(opts, true);
return { ok: true };
const outcome = await checkForUpdate(opts, false, true);
if (outcome === undefined) return { ok: true };
if (outcome.status === "error") return { ok: false, error: outcome.note ?? "registry check failed" };
return { ok: true, ...outcome };
} catch (e) {
loggerLog("warn", `[update] manual web check failed: ${String(e)}`);
return { ok: false, error: String(e) };
Expand All @@ -102,7 +110,7 @@ export async function installVersionAction(v: string): Promise<{ ok: boolean; er
// Same resolution the background loop uses: explicit override wins
// (test seam), otherwise walk up from the running module (#1628).
const dir = opts.installDir ?? (await findInstallDir(opts.packageName));
const result = await forceInstallVersion(v, dir, opts, "web-panel");
const result = await forceInstallVersion(v, dir, opts, "web-panel", "manual-web");
loggerLog(result.ok ? "info" : "warn", `[update] web panel install ${v}: ${result.ok ? "installed — restart the host to finish" : `failed (${result.error})`}`);
return result;
} catch (e) {
Expand Down
Loading
Loading