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
1 change: 1 addition & 0 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,7 @@ Environment variables take precedence over the config file. They are useful for
| `ACP_UPSTREAM` | Override the default upstream base URL. |
| `ACP_LOG` | Set to `0` to disable request logging. |
| `ACP_AUTO_UPDATE` | Set to `0` to disable auto-update checks. |
| `ACP_UPDATE_TAG` | Dist-tag channel the auto-updater follows (default `latest`, e.g. `dev`). File-config key: `updateTag`. A `pr-N` preview tag is only followed when explicitly configured. |
| `ACP_PROVIDERS` | Path to an external `providers.json` (legacy / shared file). |
| `BILI_REPLAY_RETRY_BASE_MS` | Base backoff delay (ms) for acp-loop replay retries after a transient upstream rejection (default `1500`; set `0` to disable the delay). See #189. |
| `BILI_REPLAY_RETRY_MAX` | Total attempts for acp-loop replay retries (default `3`; set `1` to disable retries entirely — legacy fail-fast behavior). See #189. |
Expand Down
1 change: 1 addition & 0 deletions CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,7 @@
| `ACP_UPSTREAM` | 覆盖默认上游 base URL。 |
| `ACP_LOG` | 设为 `0` 关闭请求日志。 |
| `ACP_AUTO_UPDATE` | 设为 `0` 禁用自动更新检查。 |
| `ACP_UPDATE_TAG` | 自动更新跟随的 dist-tag 通道(默认 `latest`,如 `dev`)。文件配置键:`updateTag`。`pr-N` 预览 tag 仅在显式配置时才会被跟随。 |
| `ACP_PROVIDERS` | 指向外部 `providers.json` 的路径(旧版 / 共享文件)。 |
| `BILI_REPLAY_RETRY_BASE_MS` | acp-loop 回放重试的基础退避延迟(毫秒):上游瞬时拒绝后重试(默认 `1500`;设 `0` 关闭延迟)。见 #189。 |
| `BILI_REPLAY_RETRY_MAX` | acp-loop 回放重试的总次数(默认 `3`;设 `1` 彻底关闭重试 —— 旧版 fail-fast 行为)。见 #189。 |
Expand Down
9 changes: 7 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,19 +378,23 @@ export async function main(): Promise<void> {
// Manual one-shot update — bypasses the throttle. Apply flag
// overrides first so `-F <proxy>` reaches loadOptions; the registry
// and tarball egress then honor the same upstream-proxy decision as
// model traffic (#609).
// model traffic (#609), and the configured channel (updateTag) so
// `bili update` follows the same dist-tag as the background
// auto-updater.
for (const [k, v] of Object.entries(overrides)) {
if (v !== undefined) process.env[k] = v;
}
let updaterResolveProxy: ((url: string) => string | undefined) | undefined;
let updateTag: string | undefined;
try {
const o = loadOptions();
updaterResolveProxy = (url) => resolveProxy(o.routes, o.proxy, url, o.proxyFallback);
updateTag = o.updateTag;
} catch (e) {
console.error(`bili update: config load failed (${String(e)}); updater egress goes direct`);
}
await checkForUpdate(
{ packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true, resolveProxy: updaterResolveProxy },
{ packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true, resolveProxy: updaterResolveProxy, updateTag },
true,
);
return;
Expand Down Expand Up @@ -430,6 +434,7 @@ export async function main(): Promise<void> {
currentVersion: VERSION,
autoUpdate: true,
resolveProxy: (url) => resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback),
updateTag: opts.updateTag,
});
}
}
5 changes: 5 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,8 @@ export type ProxyOptions = {
* Drives the #405 boot warning and the web panel's source display. */
passthroughSource: "env" | "file" | null;
autoUpdate: boolean;
/** Dist-tag channel the auto-updater follows (default "latest"). */
updateTag: string;
logFile?: string;
/** MITM transparent-proxy mode. When enabled, an HTTP CONNECT handler is
* attached so clients that only know how to set HTTP_PROXY (ZCode with a
Expand Down Expand Up @@ -430,6 +432,7 @@ export function loadOptions(env: NodeJS.ProcessEnv = process.env): ProxyOptions
passthrough: passthrough.enabled,
passthroughSource: passthrough.source,
autoUpdate: (env.ACP_AUTO_UPDATE ?? (fileConfig.autoUpdate === false ? "0" : "1")) !== "0",
updateTag: (env.ACP_UPDATE_TAG ?? fileConfig.updateTag ?? "latest").trim() || "latest",
logFile: env.ACP_LOG_FILE !== undefined ? (env.ACP_LOG_FILE || undefined) : fileConfig.logFile,
mitm: {
enabled: (env.BILI_MITM ?? (fileConfig.mitm?.enabled === false ? "0" : "1")) !== "0",
Expand Down Expand Up @@ -461,6 +464,8 @@ type FileConfig = {
dumpSse?: string;
passthrough?: boolean;
autoUpdate?: boolean;
/** Dist-tag channel the auto-updater follows (default "latest"). */
updateTag?: string;
upstreamProxy?: string;
upstreamProxyMode?: string;
logFile?: string;
Expand Down
76 changes: 62 additions & 14 deletions src/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ import { proxyDispatcher } from "./upstream-proxy.js";
import type { FetchOptions } from "./fetch-util.js";

const REGISTRY_BASE = "https://registry.npmjs.org";

/** Normalize a configured dist-tag channel: absent/blank → "latest". */
export function normalizeUpdateTag(tag: string | undefined): string {
return (tag ?? "latest").trim() || "latest";
}

/** Registry URL for a package's dist-tag document (exported for tests). */
export function registryUrlFor(packageName: string, tag: string): string {
return `${REGISTRY_BASE}/${packageName}/${encodeURIComponent(tag)}`;
}
const CHECK_INTERVAL_MS = 3 * 60 * 1000;
const THROTTLE_FILE = path.join(cacheDir(), ".update-check");
const LOCK_FILE = path.join(cacheDir(), ".update-lock");
Expand All @@ -53,29 +63,59 @@ let timer: ReturnType<typeof setInterval> | undefined;
let inFlight = false;
let firstCheckDone = false;

function parseVersion(v: string): number[] {
return v.replace(/^v/, "").split(".").map((n) => parseInt(n, 10) || 0);
}
// --- Version comparison (ported from opencode-acp lib/update.ts) ---
// Proper semver including prerelease ordering: a prerelease is OLDER than its
// release (0.1.46-pr.202.1 < 0.1.46), and prerelease parts compare
// numeric-then-lexicographic. The old 3-part numeric compare mis-ordered
// prereleases and multi-digit segments.
export function isVersionNewer(latest: string, current: string): boolean {
const next = parseSemVer(latest);
const prev = parseSemVer(current);
if (!next || !prev) return false;

function isNewer(latest: string, current: string): boolean {
const l = parseVersion(latest);
const c = parseVersion(current);
for (let i = 0; i < 3; i++) {
const lv = l[i] ?? 0;
const cv = c[i] ?? 0;
if (lv > cv) return true;
if (lv < cv) return false;
const a = next.parts[i] ?? 0;
const b = prev.parts[i] ?? 0;
if (a !== b) return a > b;
}

if (!next.pre.length && prev.pre.length) return true;
if (next.pre.length && !prev.pre.length) return false;

for (let i = 0; i < Math.max(next.pre.length, prev.pre.length); i++) {
const a = next.pre[i];
const b = prev.pre[i];
if (a === undefined) return false;
if (b === undefined) return true;
if (a === b) continue;

const aNumber = /^\d+$/.test(a) ? Number(a) : undefined;
const bNumber = /^\d+$/.test(b) ? Number(b) : undefined;
if (aNumber !== undefined && bNumber !== undefined) return aNumber > bNumber;
if (aNumber !== undefined) return false;
if (bNumber !== undefined) return true;
return a > b;
}

return false;
}

function parseSemVer(version: string): { parts: number[]; pre: string[] } | undefined {
const match = version.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.+)?$/);
if (!match) return undefined;
return {
parts: [Number(match[1]), Number(match[2]), Number(match[3])],
pre: match[4]?.split(".") ?? [],
};
}

/** Stale-install decision for the up-to-date branch of an update check —
* exported for tests. "restart" means the on-disk install is newer than the
* running process: an auto-update landed in-place but the process was never
* restarted, so the one-time "Restart to finish" message is long gone and
* every "up to date" line since has been misleading (#327). */
export function staleInstallStatus(diskVersion: string | undefined, runningVersion: string): "restart" | "current" {
return diskVersion !== undefined && isNewer(diskVersion, runningVersion) ? "restart" : "current";
return diskVersion !== undefined && isVersionNewer(diskVersion, runningVersion) ? "restart" : "current";
}

async function readLastCheck(): Promise<number> {
Expand Down Expand Up @@ -337,6 +377,9 @@ export type UpdateOptions = {
* wires in bili's upstream-proxy decision chain so updater fetches honor
* the same routing (incl. NO_PROXY) as model traffic. Absent = direct. */
resolveProxy?: (url: string) => string | undefined;
/** Dist-tag channel to follow (default "latest"), e.g. "dev", "stable".
* Publishing a PR (pr-N tag) never pulls a user on another channel. */
updateTag?: string;
};

/** Fetch dispatcher for updater egress (#609). undici's global fetch ignores
Expand Down Expand Up @@ -384,7 +427,12 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis

loggerLog("info", `[update] checking npm registry for ${opts.packageName}${sinceLastSec < 0 ? " (startup check)" : sinceLastSec === 0 ? "" : ` (last check ${sinceLastSec}s ago)`}\u2026`);

const url = `${REGISTRY_BASE}/${opts.packageName}/latest`;
// Follow the configured dist-tag channel (default "latest"): an
// `updateTag: "dev"` install tracks `dev`, "stable" tracks "stable",
// etc. PR previews (pr-N tags) are only followed if explicitly
// configured, so publishing a PR never pulls a stable user forward.
const tag = normalizeUpdateTag(opts.updateTag);
const url = registryUrlFor(opts.packageName, tag);
const registryDispatcher = egressDispatcher(opts, url);
const res = await fetchWithEgress(url, {
signal: AbortSignal.timeout(5000),
Expand All @@ -410,11 +458,11 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis
const diskVersion = installDir ? await readDiskVersion(installDir) : undefined;
const currentVersion = diskVersion ?? opts.currentVersion;

if (!isNewer(latest, currentVersion)) {
if (!isVersionNewer(latest, currentVersion)) {
if (staleInstallStatus(diskVersion, opts.currentVersion) === "restart") {
loggerLog("warn", `[update] running v${opts.currentVersion} but v${diskVersion} is installed — restart bili to activate (auto-update replaced the on-disk install; this process is still on the old code)`);
} else {
loggerLog("info", `[update] current=${currentVersion} latest=${latest} (up to date)`);
loggerLog("info", `[update] current=${currentVersion} latest=${latest} tag=${tag} (up to date)`);
}
return;
}
Expand Down
42 changes: 42 additions & 0 deletions tests/update-channel.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { isVersionNewer, normalizeUpdateTag, registryUrlFor } from "../src/update.ts";

test("isVersionNewer compares numeric segments", () => {
assert.equal(isVersionNewer("0.1.43", "0.1.41"), true);
assert.equal(isVersionNewer("0.1.41", "0.1.43"), false);
assert.equal(isVersionNewer("0.1.41", "0.1.41"), false);
assert.equal(isVersionNewer("0.2.0", "0.10.0"), false);
assert.equal(isVersionNewer("1.0.0", "0.9.9"), true);
assert.equal(isVersionNewer("v1.2.3", "1.2.2"), true);
});

test("isVersionNewer handles prerelease ordering (pre < release, numeric pre parts)", () => {
// A prerelease is OLDER than its release: 0.1.46-pr.202.1 < 0.1.46
assert.equal(isVersionNewer("0.1.46", "0.1.46-pr.202.1"), true);
assert.equal(isVersionNewer("0.1.46-pr.202.1", "0.1.46"), false);
// Higher prerelease number is newer
assert.equal(isVersionNewer("0.1.46-pr.203.1", "0.1.46-pr.202.1"), true);
// A release is newer than any prerelease of a lower version
assert.equal(isVersionNewer("0.1.47", "0.1.46-pr.999.1"), true);
});

test("registryUrlFor follows the configured dist-tag channel", () => {
assert.equal(registryUrlFor("billion-context", "dev"), "https://registry.npmjs.org/billion-context/dev");
assert.equal(registryUrlFor("billion-context", "stable"), "https://registry.npmjs.org/billion-context/stable");
});

test("normalizeUpdateTag defaults to latest and trims/blank-folds", () => {
assert.equal(normalizeUpdateTag(undefined), "latest");
assert.equal(normalizeUpdateTag(" "), "latest");
assert.equal(normalizeUpdateTag("dev"), "dev");
assert.equal(normalizeUpdateTag(" dev "), "dev");
});

test("registryUrlFor encodes exotic tag names and only follows them when explicitly configured", () => {
// PR preview tags (pr-N) are distinct dist-tags — a stable install keeps
// fetching /latest; the URL only becomes /pr-592 when the user opts in.
assert.equal(registryUrlFor("billion-context", "pr-592"), "https://registry.npmjs.org/billion-context/pr-592");
assert.notEqual(registryUrlFor("billion-context", normalizeUpdateTag(undefined)), "https://registry.npmjs.org/billion-context/pr-592");
assert.equal(registryUrlFor("billion-context", "we ird+tag"), "https://registry.npmjs.org/billion-context/we%20ird%2Btag");
});
Loading