Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(local-installation): resolve one download region and order every download by it

Dongdong Chen63a918c4af1a
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index 87a7f754..c3378c6b 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -52,7 +52,8 @@ Gateway and runs Agents. The daemon exits with the app.
status summary, tray menu and tray icons, drawn from the logo PNGs in
`resources/tray/` with a status badge.
- `src/main/local-server.ts`: LocalServer, the setup page's Quick Install
- path. It fetches the pinned Node runtime and unpacks the linger source package
+ path. It fetches the pinned Node runtime (sources in the download region's
+ order, `scripts/installs/README.md`) and unpacks the linger source package
into the install location (the default home, or a folder picked under
Customize; tar runs inside the target with relative paths, and the
finished folder is moved into place with `renameRetrying`, which waits out
diff --git a/apps/desktop/distribution/darwin-arm64.json b/apps/desktop/distribution/darwin-arm64.json
index 391fb54b..f3cded99 100644
--- a/apps/desktop/distribution/darwin-arm64.json
+++ b/apps/desktop/distribution/darwin-arm64.json
@@ -3,6 +3,10 @@
"arch": "arm64",
"localmodelsTool": {
"url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev40/darwin-arm64.tgz",
+ "mirrors": [
+ "https://registry.npmjs.org/@simplexai/localmodels-darwin-arm64/-/localmodels-darwin-arm64-0.1.0-dev.40.tgz",
+ "https://cdn.npmmirror.com/packages/@simplexai/localmodels-darwin-arm64/0.1.0-dev.40/localmodels-darwin-arm64-0.1.0-dev.40.tgz"
+ ],
"sha256": "648e8909915d8da2b87ae4f4797cd22f2d46d8a7cd025287ab9e6b5436119687",
"bytes": 14953559,
"sourceCommit": "a4de3e359d2a4f9b654f9ae7bdf6887c55896b7d",
diff --git a/apps/desktop/distribution/linux-x64.json b/apps/desktop/distribution/linux-x64.json
index ad7b3ee7..71a83e3c 100644
--- a/apps/desktop/distribution/linux-x64.json
+++ b/apps/desktop/distribution/linux-x64.json
@@ -3,6 +3,10 @@
"arch": "x64",
"localmodelsTool": {
"url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev40/linux-x64.tgz",
+ "mirrors": [
+ "https://registry.npmjs.org/@simplexai/localmodels-linux-x64/-/localmodels-linux-x64-0.1.0-dev.40.tgz",
+ "https://cdn.npmmirror.com/packages/@simplexai/localmodels-linux-x64/0.1.0-dev.40/localmodels-linux-x64-0.1.0-dev.40.tgz"
+ ],
"sha256": "a8e176fa426360f489bf9c552064faf7e1dd88072b463a13185ff1193a223683",
"bytes": 20790291,
"sourceCommit": "a4de3e359d2a4f9b654f9ae7bdf6887c55896b7d",
diff --git a/apps/desktop/distribution/win32-x64.json b/apps/desktop/distribution/win32-x64.json
index 26966b59..5d3f22b4 100644
--- a/apps/desktop/distribution/win32-x64.json
+++ b/apps/desktop/distribution/win32-x64.json
@@ -3,6 +3,10 @@
"arch": "x64",
"localmodelsTool": {
"url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev40/win32-x64.tgz",
+ "mirrors": [
+ "https://registry.npmjs.org/@simplexai/localmodels-win32-x64/-/localmodels-win32-x64-0.1.0-dev.40.tgz",
+ "https://cdn.npmmirror.com/packages/@simplexai/localmodels-win32-x64/0.1.0-dev.40/localmodels-win32-x64-0.1.0-dev.40.tgz"
+ ],
"sha256": "de07306075b5efbf2158c41a7c87fe4939bac45b9b6f953270ed00017a6540be",
"bytes": 23191788,
"sourceCommit": "a4de3e359d2a4f9b654f9ae7bdf6887c55896b7d",
diff --git a/apps/desktop/scripts/build-native-runtime.mjs b/apps/desktop/scripts/build-native-runtime.mjs
index 702e687f..197fbbfe 100644
--- a/apps/desktop/scripts/build-native-runtime.mjs
+++ b/apps/desktop/scripts/build-native-runtime.mjs
@@ -91,6 +91,7 @@ export const MODEL_PACKAGE_GROUPS = [
export const modelPackageGroup = (name) =>
MODEL_PACKAGE_GROUPS.find(([pattern]) => pattern.test(name))?.[1];
// Registries holding the same tarballs; the lockfile integrity checks both.
+// Node Services tries the one in its download region (SIMPLEX_REGION) first.
const MODEL_REGISTRIES = [
"https://registry.npmjs.org/",
"https://registry.npmmirror.com/",
diff --git a/apps/desktop/src/main/distribution.test.ts b/apps/desktop/src/main/distribution.test.ts
index 13638601..f45d3455 100644
--- a/apps/desktop/src/main/distribution.test.ts
+++ b/apps/desktop/src/main/distribution.test.ts
@@ -66,5 +66,13 @@ describe("desktop distributions", () => {
);
const kit = pin(`STACK_KIT_${target.replace("-", "_")}`);
if (kit) expect(tool.sha256).toBe(kit);
+ // The same kit as published on npm (and its China mirror), in the
+ // stack's npm version; the pinned sha256 decides either way.
+ const name = `localmodels-${target}`;
+ const version = pin("STACK_NPM_VERSION");
+ expect(tool.mirrors).toEqual([
+ `https://registry.npmjs.org/@simplexai/${name}/-/${name}-${version}.tgz`,
+ `https://cdn.npmmirror.com/packages/@simplexai/${name}/${version}/${name}-${version}.tgz`,
+ ]);
});
});
diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts
index da6cf2b3..72188a19 100644
--- a/apps/desktop/src/main/local-server.ts
+++ b/apps/desktop/src/main/local-server.ts
@@ -33,7 +33,7 @@ import {
readLocalIdentity,
readLocalLogin,
} from "@linger/local-installation/account";
-import { downloadVerified } from "@linger/local-installation/download";
+import { downloadInRegion } from "@linger/local-installation/region";
import { latestLegacyBackup } from "@linger/local-installation/legacy-database";
import { legacyMigrationPending } from "@linger/local-installation/home";
import { validateSourceRepository } from "@linger/local-installation/source-checkout";
@@ -1900,7 +1900,9 @@ export class LocalServerModule implements Module {
// Downloads a verified archive and unpacks its single top-level folder
// into `directory`, which appears only once complete; `marker` is a file
- // every complete one has.
+ // every complete one has. Sources in the installation's download region
+ // come first (nodejs.org or its China mirror for Node.js), and the
+ // installer it starts reads the region resolved here.
async #unpack(
archive: {
url: string;
@@ -1921,7 +1923,8 @@ export class LocalServerModule implements Module {
);
const unpacked = `${directory}.partial`;
try {
- await downloadVerified(
+ await downloadInRegion(
+ this.#location ?? this.#home,
{
url: archive.url,
...(archive.mirrors && { mirrors: archive.mirrors }),
diff --git a/apps/node-services/src/model-packages.ts b/apps/node-services/src/model-packages.ts
index 55e44ba6..c4af05d7 100644
--- a/apps/node-services/src/model-packages.ts
+++ b/apps/node-services/src/model-packages.ts
@@ -3,6 +3,7 @@ import { existsSync, readFileSync } from "node:fs";
import { mkdir, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { gunzipSync } from "node:zlib";
+import { orderByRegion, type Region } from "@linger/service-kit";
import { mirrorHome, packageRoot } from "./paths.js";
@@ -20,7 +21,10 @@ export interface ModelPackage {
version: string;
/** The lockfile's Subresource Integrity of the tarball (sha512). */
integrity: string;
- /** Registry URLs of the same tarball, tried in order. */
+ /**
+ * Registry URLs of the same tarball, tried in order after those in the
+ * download region.
+ */
tarballs: string[];
}
@@ -112,7 +116,7 @@ const failed = new Map<string, { at: number; error: unknown }>();
export async function installModelPackages(
names: string[],
environment: NodeJS.ProcessEnv = process.env,
- options: { fetch?: typeof fetch; timeoutMs?: number } = {},
+ options: { fetch?: typeof fetch; timeoutMs?: number; region?: Region } = {},
): Promise<void> {
for (const name of names) {
if (modelPackagesInstalled([name], environment)) continue;
@@ -176,7 +180,7 @@ async function install(
name: string,
item: ModelPackage,
environment: NodeJS.ProcessEnv,
- options: { fetch?: typeof fetch; timeoutMs?: number },
+ options: { fetch?: typeof fetch; timeoutMs?: number; region?: Region },
): Promise<void> {
const root = modelPackagesRoot(environment);
const directory = path.join(root, name);
@@ -214,13 +218,13 @@ async function install(
async function download(
name: string,
item: ModelPackage,
- options: { fetch?: typeof fetch; timeoutMs?: number },
+ options: { fetch?: typeof fetch; timeoutMs?: number; region?: Region },
): Promise<Buffer> {
const [algorithm, expected] = item.integrity.split(/-(.*)/s);
if (algorithm !== "sha512" || !expected)
throw new Error(`Model package ${name} has no sha512 integrity`);
const errors: string[] = [];
- for (const url of item.tarballs) {
+ for (const url of orderByRegion(options.region ?? "global", item.tarballs)) {
try {
const response = await (options.fetch ?? fetch)(url, {
signal: AbortSignal.timeout(options.timeoutMs ?? 10 * 60_000),
diff --git a/apps/node-services/src/voice/config.ts b/apps/node-services/src/voice/config.ts
index fcf9173b..2ca8d714 100644
--- a/apps/node-services/src/voice/config.ts
+++ b/apps/node-services/src/voice/config.ts
@@ -1,3 +1,4 @@
+import type { Region } from "@linger/service-kit";
import { serviceCredential } from "@linger/service-kit/node";
import { teamHubBaseUrl } from "../teamhub-base-url.js";
@@ -7,6 +8,11 @@ export interface VoiceConfig {
readonly teamHubCredential: string | undefined;
/** Authenticates TeamHub's reconcile notifications. */
readonly managementCredential: string | undefined;
+ /**
+ * The download region the installer resolved (SIMPLEX_REGION); model
+ * packages come from its registry first. Global when unset.
+ */
+ readonly region: Region;
}
export function readVoiceConfig(environment: NodeJS.ProcessEnv): VoiceConfig {
@@ -17,5 +23,6 @@ export function readVoiceConfig(environment: NodeJS.ProcessEnv): VoiceConfig {
"node-services-internal",
environment,
),
+ region: environment.SIMPLEX_REGION === "cn" ? "cn" : "global",
});
}
diff --git a/apps/node-services/src/voice/service.ts b/apps/node-services/src/voice/service.ts
index 46a0d34c..0ef35d3f 100644
--- a/apps/node-services/src/voice/service.ts
+++ b/apps/node-services/src/voice/service.ts
@@ -148,7 +148,8 @@ export async function startVoiceService(options: {
// workers wait for its first download and find it on NODE_PATH.
const models = modelPackageNames("voice");
const installModels =
- options.installModels ?? (() => installModelPackages(models, env));
+ options.installModels ??
+ (() => installModelPackages(models, env, { region: config.region }));
// Worker starts share one download, so concurrent starts never fetch twice.
let installing: Promise<void> | undefined;
const install = () =>
diff --git a/apps/node-services/tests/model-packages.test.ts b/apps/node-services/tests/model-packages.test.ts
index a07a21f3..6de996bf 100644
--- a/apps/node-services/tests/model-packages.test.ts
+++ b/apps/node-services/tests/model-packages.test.ts
@@ -163,6 +163,37 @@ describe("model packages", () => {
).toBe(true);
});
+ it("tries the registry of its download region first", async () => {
+ writeFileSync(
+ path.join(runtime.packageRoot, "models.json"),
+ JSON.stringify({
+ packages: {
+ "@livekit/local-inference-darwin-arm64": {
+ group: "voice",
+ version: "0.2.7",
+ integrity: integrity(turn),
+ tarballs: [
+ "https://registry.npmjs.org/turn-0.2.7.tgz",
+ "https://registry.npmmirror.com/turn-0.2.7.tgz",
+ ],
+ },
+ },
+ }),
+ );
+ const models = await load();
+ const fetch = vi.fn(
+ async (_url: string) => new Response(new Uint8Array(turn)),
+ );
+ await models.installModelPackages(
+ ["@livekit/local-inference-darwin-arm64"],
+ environment,
+ { fetch: fetch as typeof globalThis.fetch, region: "cn" },
+ );
+ expect(fetch.mock.calls.map(([url]) => url)).toEqual([
+ "https://registry.npmmirror.com/turn-0.2.7.tgz",
+ ]);
+ });
+
it("shares one download between callers and waits a minute after a failure", async () => {
const models = await load();
let release!: () => void;
@@ -345,6 +376,51 @@ describe("features that need model packages", () => {
await service.stop();
});
+ it("download the voice packages from the installer's region first", async () => {
+ writeFileSync(
+ path.join(runtime.packageRoot, "models.json"),
+ JSON.stringify({
+ packages: {
+ "@livekit/local-inference-linux-x64-gnu": {
+ group: "voice",
+ version: "0.2.7",
+ integrity: integrity(vad),
+ tarballs: [
+ "https://registry.npmjs.org/vad-0.2.7.tgz",
+ "https://registry.npmmirror.com/vad-0.2.7.tgz",
+ ],
+ },
+ },
+ }),
+ );
+ const { startVoiceService } = await import("../src/voice/service.js");
+ const download = vi.fn(
+ async (_url: string) => new Response(new Uint8Array(vad)),
+ );
+ vi.stubGlobal("fetch", download);
+ try {
+ const service = await startVoiceService({
+ logger: { log: vi.fn() } as unknown as JsonLogger,
+ http: { mount: () => () => {} } as unknown as HttpHost,
+ environment: {
+ ...environment,
+ SIMPLEX_REGION: "cn",
+ LINGER_SECRET_SEED: "model-packages-test-seed-0123456789abcdef",
+ },
+ fetch: async () => Response.json({}),
+ spawnWorker: vi.fn(),
+ });
+ await vi.waitFor(() =>
+ expect(download.mock.calls.map(([url]) => url)).toEqual([
+ "https://registry.npmmirror.com/vad-0.2.7.tgz",
+ ]),
+ );
+ await service.stop();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
it("log a failed background download and retry it when a key arrives", async () => {
const { startVoiceService } = await import("../src/voice/service.js");
const models = await load();
diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md
index 6e3c2bde..f16a9588 100644
--- a/packages/local-installation/AGENTS.md
+++ b/packages/local-installation/AGENTS.md
@@ -152,6 +152,14 @@ under a lease no record holds, once its environment proves that lease; an
attempt that failed or was killed before keeping a record would otherwise
leave PostgreSQL holding `postmaster.pid` against every retry.
+Every download offered by both a global host and a mainland-China mirror
+goes through `downloadInRegion` (`region.ts`), which tries the home's
+download region first and never drops a source; the region is
+`SIMPLEX_REGION`, else `<home>/runtime/region.json` (7 days), else the npm
+registry probe, and a fallback to the other region rewrites the file. The
+resolved region reaches every `localmodels` child and native service as
+`SIMPLEX_REGION`. The contract is in `scripts/installs/README.md`.
+
Move a freshly downloaded or unpacked file or folder into place with
`renameRetrying` from `fs-retry.ts`: on Windows antivirus and indexing hold
new files for a moment, and a plain rename then fails with EPERM.
diff --git a/packages/local-installation/package.json b/packages/local-installation/package.json
index ff95435a..3dca3c05 100644
--- a/packages/local-installation/package.json
+++ b/packages/local-installation/package.json
@@ -18,6 +18,7 @@
"lint": "eslint --max-warnings=0 src"
},
"dependencies": {
+ "@linger/service-kit": "workspace:*",
"tar": "7.5.22"
}
}
diff --git a/packages/local-installation/src/download.ts b/packages/local-installation/src/download.ts
index a14f0d54..74f37fee 100644
--- a/packages/local-installation/src/download.ts
+++ b/packages/local-installation/src/download.ts
@@ -41,7 +41,7 @@ function publicUrl(value: string) {
* Only a verified, bounded download may become an installation input. A
* failed, slow or interrupted transfer moves on to the next mirror and
* resumes there with an HTTP range request; the checksum still decides what
- * is published.
+ * is published. Resolves to the URL that delivered the last bytes.
*/
export async function downloadVerified(
options: {
@@ -59,7 +59,7 @@ export async function downloadVerified(
},
fetcher: typeof fetch = fetch,
timing: DownloadTiming = defaultTiming,
-) {
+): Promise<string> {
const urls = [options.url, ...(options.mirrors ?? [])].map(publicUrl);
const digestLength = options.algorithm === "sha256" ? 64 : 128;
if (!new RegExp(`^[a-f0-9]{${digestLength}}$`).test(options.digest))
@@ -184,6 +184,7 @@ export async function downloadVerified(
};
let published = false;
+ let served = urls[0]!;
try {
let result: "done" | "retry" | "next" = "next";
// Hosts that cannot serve the file leave the rotation.
@@ -196,6 +197,7 @@ export async function downloadVerified(
});
for (const url of active) {
result = await attempt(url);
+ served = url;
if (result === "done") break rounds;
if (result === "next") active = active.filter((item) => item !== url);
}
@@ -216,6 +218,7 @@ export async function downloadVerified(
signal: options.signal,
});
published = true;
+ return served.href;
} finally {
await handle.close().catch(() => {});
// A resumable download keeps what it received for the next call.
diff --git a/packages/local-installation/src/localmodels-tool.test.ts b/packages/local-installation/src/localmodels-tool.test.ts
index c4c47454..ab2b95a1 100644
--- a/packages/local-installation/src/localmodels-tool.test.ts
+++ b/packages/local-installation/src/localmodels-tool.test.ts
@@ -17,6 +17,8 @@ import { createHash } from "node:crypto";
import path from "node:path";
import os from "node:os";
import { withInstanceLock, type Instance } from "./instance.js";
+import { REGION_SCHEMA, regionFile } from "./region.js";
+import { requestUrlText } from "@linger/service-kit";
import { afterEach, expect, test, vi } from "vitest";
import {
ensureLocalmodelsTool,
@@ -46,6 +48,17 @@ const hash = (b: string | Buffer) =>
async function fixture() {
const home = await mkdtemp(path.join(os.tmpdir(), "linger-model-tool-"));
roots.push(home);
+ // A region resolved earlier, so no test probes the registries.
+ await mkdir(path.dirname(regionFile(home)), { recursive: true });
+ await writeFile(
+ regionFile(home),
+ JSON.stringify({
+ schema: REGION_SCHEMA,
+ region: "global",
+ resolved_at: new Date().toISOString(),
+ method: "probe",
+ }),
+ );
const manifest = {
schemaVersion: 1,
platform: process.platform,
@@ -279,6 +292,44 @@ test.skipIf(process.platform === "win32")(
);
},
);
+test.skipIf(process.platform === "win32")(
+ "downloads the kit from the npm China mirror first in the cn region",
+ async () => {
+ const f = await fixture();
+ const bytes = await packed(f);
+ const npm = "https://registry.npmjs.org/@simplexai/kit/-/kit-1.tgz";
+ const mirror =
+ "https://cdn.npmmirror.com/packages/@simplexai/kit/1/kit-1.tgz";
+ const source = {
+ ...f.source,
+ mirrors: [npm, mirror],
+ sha256: hash(bytes),
+ bytes: bytes.length,
+ };
+ await writeFile(
+ regionFile(f.home),
+ JSON.stringify({
+ schema: REGION_SCHEMA,
+ region: "cn",
+ resolved_at: new Date().toISOString(),
+ method: "probe",
+ }),
+ );
+ const requested: string[] = [];
+ await ensureLocalmodelsTool(
+ f.home,
+ {},
+ {
+ source,
+ fetcher: async (url) => {
+ requested.push(requestUrlText(url));
+ return new Response(bytes);
+ },
+ },
+ );
+ expect(requested).toEqual([mirror]);
+ },
+);
// A refused member must reject the install, not leave the extraction pending.
for (const [label, add] of [
[
@@ -354,6 +405,41 @@ test("invokes the verified upstream module with isolated module and state paths"
"sourceCommit",
);
});
+test("passes the resolved download region to every localmodels child", async () => {
+ const f = await fixture();
+ vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", JSON.stringify(f.source));
+ // The home's saved region decides: an inherited auto is replaced, so the
+ // child never probes again.
+ vi.stubEnv("SIMPLEX_REGION", "auto");
+ await writeFile(
+ regionFile(f.home),
+ JSON.stringify({
+ schema: REGION_SCHEMA,
+ region: "cn",
+ resolved_at: new Date().toISOString(),
+ method: "fallback",
+ }),
+ );
+ const run = vi.fn(async () => ({ code: 0, stdout: "{}", stderr: "" }));
+ for (const args of [
+ ["stack", "apply", "--json"],
+ ["foundations", "start", "--json"],
+ ["harness", "apply", "plan", "--jsonl"],
+ ])
+ await runLocalmodels(
+ f.home,
+ args,
+ { env: { SIMPLEX_REGION: "global" } },
+ { run },
+ );
+ expect(run).toHaveBeenCalledTimes(3);
+ for (const call of run.mock.calls as unknown as [
+ string,
+ string[],
+ { env: NodeJS.ProcessEnv },
+ ][])
+ expect(call[2].env.SIMPLEX_REGION).toBe("cn");
+});
// What `library status` prints, cut to the fields the stop reads.
const libraryStatus = (models: { id: string; state: string }[]) => ({
code: 0,
diff --git a/packages/local-installation/src/localmodels-tool.ts b/packages/local-installation/src/localmodels-tool.ts
index 5ef8ab31..567b0dcf 100644
--- a/packages/local-installation/src/localmodels-tool.ts
+++ b/packages/local-installation/src/localmodels-tool.ts
@@ -3,7 +3,7 @@ import { createReadStream } from "node:fs";
import { lstat, readdir, readFile, rename, rm, chmod } from "node:fs/promises";
import path from "node:path";
import { x as extract } from "tar";
-import { downloadVerified } from "./download.js";
+import { downloadInRegion, resolveRegion } from "./region.js";
import {
atomicPrivate,
privateDirectory,
@@ -323,7 +323,8 @@ async function prepareLocalmodelsTool(
? "Repairing the model and Harness installation tool…"
: "Preparing the model and Harness installation tool…",
});
- await downloadVerified(
+ await downloadInRegion(
+ home,
{
url: source.url,
mirrors: source.mirrors,
@@ -427,6 +428,8 @@ export async function runLocalmodels(
const env: NodeJS.ProcessEnv = {
...process.env,
...options.env,
+ // localmodels downloads from the same region and does not probe again.
+ SIMPLEX_REGION: await resolveRegion(home, { signal: options.signal }),
PYTHONPATH: tool.moduleDir,
LOCALMODELS_STATE: state,
PYTHONNOUSERSITE: "1",
diff --git a/packages/local-installation/src/native-dependencies.test.ts b/packages/local-installation/src/native-dependencies.test.ts
index 7c9c29f1..e98327dc 100644
--- a/packages/local-installation/src/native-dependencies.test.ts
+++ b/packages/local-installation/src/native-dependencies.test.ts
@@ -25,6 +25,7 @@ import {
validateNativeVoiceTools,
} from "./native-dependencies.js";
import * as downloads from "./download.js";
+import { REGION_SCHEMA, regionFile } from "./region.js";
import type { InstallerEvent } from "./events.js";
const roots: string[] = [];
afterEach(async () => {
@@ -520,6 +521,7 @@ it("prepares real executable launchers and reuses verified warm dependencies ent
? "npm"
: "postgres";
await writeFile(options.output, await readFile(archives[name]!));
+ return options.url;
});
const events: InstallerEvent[] = [];
const result = await prepareNativeDependencies({
@@ -585,6 +587,7 @@ it("prepares real executable launchers and reuses verified warm dependencies ent
? "npm"
: "postgres";
await writeFile(options.output, await readFile(archives[name]!));
+ return options.url;
});
const withoutGo = await prepareNativeDependencies({
repo,
@@ -605,6 +608,7 @@ it("prepares real executable launchers and reuses verified warm dependencies ent
if (options.url !== source.url)
throw new Error(`${options.url} downloaded`);
await writeFile(options.output, await readFile(archives.postgres!));
+ return options.url;
});
const offline = await prepareNativeDependencies({
repo,
@@ -621,6 +625,66 @@ it("prepares real executable launchers and reuses verified warm dependencies ent
);
expect(existsSync(path.join(offline.toolchainRoot, "bin/pnpm"))).toBe(false);
expect(existsSync(path.join(offline.toolchainRoot, "bin/npm"))).toBe(false);
+ // In the cn region every toolchain download, the package registry and the
+ // Go module proxy start from the China mirrors; the others stay behind.
+ const china = path.join(root, "home-cn");
+ await mkdir(path.dirname(regionFile(china)), { recursive: true });
+ await writeFile(
+ regionFile(china),
+ JSON.stringify({
+ schema: REGION_SCHEMA,
+ region: "cn",
+ resolved_at: new Date().toISOString(),
+ method: "probe",
+ }),
+ );
+ download.mockClear();
+ download.mockImplementation(async (options) => {
+ const name = options.url.includes("/go")
+ ? "go"
+ : options.url.includes("/pnpm/")
+ ? "pnpm"
+ : options.url.includes("/npm/")
+ ? "npm"
+ : "postgres";
+ await writeFile(options.output, await readFile(archives[name]!));
+ return options.url;
+ });
+ const cn = await prepareNativeDependencies({
+ repo,
+ home: china,
+ signal: new AbortController().signal,
+ });
+ expect(
+ download.mock.calls.map(([options]) => [
+ new URL(options.url).host,
+ ...(options.mirrors ?? []).map((url) => new URL(url).host),
+ ]),
+ ).toEqual([
+ ["mirrors.aliyun.com", "dl.google.com"],
+ ["cdn.npmmirror.com", "registry.npmjs.org"],
+ ["cdn.npmmirror.com", "registry.npmjs.org"],
+ ["releases.example", "mirror.example"],
+ ]);
+ expect(cn.registries).toEqual([
+ "https://registry.npmmirror.com/",
+ "https://registry.npmjs.org/",
+ ]);
+ expect(cn.env.pnpm_config_registry).toBe("https://registry.npmmirror.com/");
+ expect(cn.env.GOPROXY).toBe(
+ "https://goproxy.cn|https://proxy.golang.org|direct",
+ );
+ // A Go module proxy the person set still wins.
+ vi.stubEnv("GOPROXY", "https://proxy.example");
+ expect(
+ (
+ await prepareNativeDependencies({
+ repo,
+ home: china,
+ signal: new AbortController().signal,
+ })
+ ).env.GOPROXY,
+ ).toBe("https://proxy.example");
}, 15000);
describe("native voice tools", () => {
const voice = {
diff --git a/packages/local-installation/src/native-dependencies.ts b/packages/local-installation/src/native-dependencies.ts
index 0daf7fe8..7102b201 100644
--- a/packages/local-installation/src/native-dependencies.ts
+++ b/packages/local-installation/src/native-dependencies.ts
@@ -13,6 +13,7 @@ import {
} from "node:fs/promises";
import path from "node:path";
import { x as extract } from "tar";
+import { orderByRegion } from "@linger/service-kit";
import { downloadVerified } from "./download.js";
import {
configuredNpmRegistry,
@@ -20,8 +21,8 @@ import {
npmRegistry,
npmRegistryEnvironment,
npmTarballUrl,
- rankNpmRegistries,
} from "./npm-registry.js";
+import { downloadInRegion, resolveRegion } from "./region.js";
import { extractZip } from "./zip.js";
import {
privateDirectory,
@@ -305,13 +306,18 @@ async function copyVerified(
`The bundled ${label} archive does not match its checksum. Install Linger again.`,
);
}
-/** Content-addressed, locked installs: unverified or partial trees never become executable inputs. */
+/**
+ * Content-addressed, locked installs: unverified or partial trees never
+ * become executable inputs. With `home`, a download tries the sources in its
+ * region first (region.ts).
+ */
export async function acquireNativeArtifact(
base: string,
artifact: Artifact,
signal: AbortSignal,
onProgress?: (completed: number, total?: number) => void,
fetcher: typeof fetch = fetch,
+ home?: string,
) {
const digestLength =
artifact.algorithm === "sha256"
@@ -391,6 +397,12 @@ export async function acquireNativeArtifact(
signal,
onProgress,
});
+ else if (home)
+ await downloadInRegion(
+ home,
+ { ...artifact, output: archive, signal, onProgress },
+ fetcher,
+ );
else
await downloadVerified(
{ ...artifact, output: archive, signal, onProgress },
@@ -471,7 +483,7 @@ function shellQuote(value: string) {
return `'${value.replace(/'/g, "'\\''")}'`;
}
// Release lock: sourced from https://go.dev/dl/?mode=json&include=all on 2026-10-29.
-// The Aliyun mirror serves the same archives for hosts that cannot reach Google.
+// The Aliyun mirror serves the same archives; the download region orders them.
// Runtime preparation never resolves mutable toolchain metadata or upgrades this pin.
const pinnedGoSources: Readonly<Record<string, Artifact>> = {
"1.26.5-darwin-arm64": {
@@ -565,11 +577,20 @@ export async function prepareNativeDependencies(options: {
);
await privateDirectory(toolchainRoot);
const configuredRegistry = configuredNpmRegistry();
+ // Only downloads resolve the region: a checkout that brings its services
+ // and TeamHub binaries prepares offline.
+ const region =
+ withGo || withPackages
+ ? await resolveRegion(options.home, {
+ signal: options.signal,
+ fetcher: options.fetcher,
+ })
+ : undefined;
const registries = !withPackages
? []
: configuredRegistry
? [configuredRegistry]
- : await rankNpmRegistries(options.signal, options.fetcher);
+ : orderByRegion(region!, [npmRegistry, npmMirrorRegistry]);
if (registries[0])
options.onEvent?.({
kind: "log",
@@ -605,6 +626,7 @@ export async function prepareNativeDependencies(options: {
progress: { completed, total, unit: "bytes" },
}),
options.fetcher,
+ options.home,
);
const go = withGo
? await component(`Go ${versions.go}`, goSource!)
@@ -614,9 +636,9 @@ export async function prepareNativeDependencies(options: {
const source = npmSources[name];
// The pinned tools come from the public hosts even when installs use
// a configured registry.
- const [url, ...mirrors] = (
- configuredRegistry ? [npmRegistry, npmMirrorRegistry] : registries
- ).map((registry) => npmTarballUrl(registry, name, source.version));
+ const [url, ...mirrors] = [npmRegistry, npmMirrorRegistry].map((registry) =>
+ npmTarballUrl(registry, name, source.version),
+ );
packages[name] = await component(`${name} ${source.version}`, {
url: url!,
mirrors,
@@ -703,12 +725,18 @@ export async function prepareNativeDependencies(options: {
GOCACHE: path.join(toolchainRoot, "go-build"),
GOMODCACHE: path.join(toolchainRoot, "gopath/pkg/mod"),
GOBIN: bin,
- // Module downloads fall through to the China proxy on any error,
- // including a timeout; go.sum and the checksum database (reached
- // through the proxy) still verify every module.
+ // Module downloads fall through to the other region's proxy on any
+ // error, including a timeout; go.sum and the checksum database
+ // (reached through the proxy) still verify every module.
GOPROXY:
process.env.GOPROXY ||
- "https://proxy.golang.org|https://goproxy.cn|direct",
+ [
+ ...orderByRegion(region!, [
+ "https://proxy.golang.org",
+ "https://goproxy.cn",
+ ]),
+ "direct",
+ ].join("|"),
}),
// No service needs cgo. Without it Go never calls a C compiler, which
// on a Mac without Xcode Command Line Tools opens Apple's installer.
@@ -824,6 +852,7 @@ export async function prepareNativeVoiceTools(options: {
progress: { completed, total, unit: "bytes" },
}),
options.fetcher,
+ options.home,
);
options.onEvent?.({
kind: "log",
diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.ts
index 8f530f1e..fc866d42 100644
--- a/packages/local-installation/src/native-source-flow.test.ts
+++ b/packages/local-installation/src/native-source-flow.test.ts
@@ -30,6 +30,7 @@ import {
} from "./native-source.js";
import { localIdentityProof } from "./account.js";
import { runProcess } from "./process.js";
+import { REGION_SCHEMA, regionFile } from "./region.js";
import {
installAppleDeveloperTools,
needsAppleDeveloperTools,
@@ -137,6 +138,17 @@ afterEach(async () => {
async function fixture() {
const home = await mkdtemp(path.join(os.tmpdir(), "native-flow-"));
roots.push(home);
+ // A region resolved earlier, so no test probes the registries.
+ await mkdir(path.dirname(regionFile(home)), { recursive: true });
+ await writeFile(
+ regionFile(home),
+ JSON.stringify({
+ schema: REGION_SCHEMA,
+ region: "global",
+ resolved_at: new Date().toISOString(),
+ method: "probe",
+ }),
+ );
const repo = path.join(home, "checkout");
await mkdir(path.join(repo, "scripts"), { recursive: true });
await writeFile(path.join(repo, "scripts/source-native.mjs"), "");
@@ -484,6 +496,35 @@ test("a failed dependency install retries from the next registry and reports pac
message: "Installing dependencies: 30 of 90 packages\n",
progress: { completed: 30, total: 90, unit: "packages" },
});
+ // The China mirror worked where the global registry failed: later runs
+ // start there.
+ expect(JSON.parse(await readFile(regionFile(f.home), "utf8"))).toMatchObject({
+ region: "cn",
+ method: "fallback",
+ });
+});
+test("every native service gets the resolved download region", async () => {
+ const f = await fixture();
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ await installNativeSource({
+ ...f,
+ name: "native-flow",
+ setupChoice: "pi",
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ });
+ const services = vi
+ .mocked(startNativeProcess)
+ .mock.calls.map(([options]) => [options.name, options.env.SIMPLEX_REGION]);
+ expect(services).toEqual([
+ ["teamhub", "global"],
+ ["node-services", "global"],
+ ["web", "global"],
+ ]);
});
test("failed preparation never stops services that were already running", async () => {
const f = await fixture();
diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.ts
index 72f058db..7f5b440e 100644
--- a/packages/local-installation/src/native-source.ts
+++ b/packages/local-installation/src/native-source.ts
@@ -26,7 +26,9 @@ import {
import { readLiveKitSettings, startNativeLiveKit } from "./native-livekit.js";
import { checkNativeRuntime } from "./native-runtime.js";
import { checkTeamhubBinaries } from "./teamhub-binaries.js";
+import { sourceRegion } from "@linger/service-kit";
import { npmRegistryEnvironment } from "./npm-registry.js";
+import { recordRegionFallback, resolveRegion } from "./region.js";
import { prepareNativeDatabase } from "./native-database.js";
import {
inspectNativeListeners,
@@ -633,10 +635,15 @@ async function runNativeSource(
message:
"Voice stays off: this installation has no voice tools for this computer.\n",
});
+ // node-services downloads its voice model packages from the region's
+ // registry first, and nothing it starts probes again.
+ const region = await resolveRegion(home, { signal });
+ emit({ kind: "log", stage, message: `Download region: ${region}.\n` });
const env: NodeJS.ProcessEnv = {
...process.env,
...tools.env,
...configured.env,
+ SIMPLEX_REGION: region,
...(voice
? {
// TeamHub and the voice workers run ffmpeg and ffprobe from PATH.
@@ -775,6 +782,8 @@ async function runNativeSource(
packages,
);
registries = registries.slice(index);
+ if (index > 0)
+ await recordRegionFallback(home, sourceRegion(registry));
return;
} catch (error) {
signal.throwIfAborted();
diff --git a/packages/local-installation/src/npm-registry.test.ts b/packages/local-installation/src/npm-registry.test.ts
index eaef34dc..60316223 100644
--- a/packages/local-installation/src/npm-registry.test.ts
+++ b/packages/local-installation/src/npm-registry.test.ts
@@ -3,7 +3,7 @@ import {
configuredNpmRegistry,
npmRegistryEnvironment,
npmTarballUrl,
- rankNpmRegistries,
+ probeNpmRegistries,
} from "./npm-registry.js";
afterEach(() => vi.unstubAllEnvs());
@@ -19,7 +19,7 @@ const slow = (bytes: number) =>
it("puts the registry that delivers more of the probe first", async () => {
const requested: string[] = [];
- const order = await rankNpmRegistries(
+ const order = await probeNpmRegistries(
new AbortController().signal,
async (url, init) => {
requested.push((url as URL | string).toString());
@@ -31,8 +31,8 @@ it("puts the registry that delivers more of the probe first", async () => {
50,
);
expect(order).toEqual([
- "https://registry.npmmirror.com/",
- "https://registry.npmjs.org/",
+ { registry: "https://registry.npmmirror.com/", bytes: 4096 },
+ { registry: "https://registry.npmjs.org/", bytes: 16 },
]);
expect(requested.sort()).toEqual([
"https://cdn.npmmirror.com/packages/pnpm/11.7.0/pnpm-11.7.0.tgz",
@@ -40,16 +40,19 @@ it("puts the registry that delivers more of the probe first", async () => {
]);
});
-it("keeps the public registry first when nothing answers", async () => {
+it("measures nothing when neither registry answers", async () => {
expect(
- await rankNpmRegistries(
+ await probeNpmRegistries(
new AbortController().signal,
async () => {
throw new TypeError("fetch failed");
},
50,
),
- ).toEqual(["https://registry.npmjs.org/", "https://registry.npmmirror.com/"]);
+ ).toEqual([
+ { registry: "https://registry.npmjs.org/", bytes: 0 },
+ { registry: "https://registry.npmmirror.com/", bytes: 0 },
+ ]);
});
it("respects a configured registry and points native downloads at the mirror", () => {
diff --git a/packages/local-installation/src/npm-registry.ts b/packages/local-installation/src/npm-registry.ts
index 37e7a664..b809a2ca 100644
--- a/packages/local-installation/src/npm-registry.ts
+++ b/packages/local-installation/src/npm-registry.ts
@@ -36,15 +36,15 @@ export function configuredNpmRegistry() {
}
/**
- * Orders the public registry and its China mirror by how many bytes of the
- * same tarball each delivers within the probe window. A registry that cannot
- * be reached at all goes last; the install still falls back to it.
+ * Measures how many bytes of the same tarball the public registry and its
+ * China mirror each deliver within the probe window, most first; -1 when a
+ * registry refused. region.ts decides the download region from it.
*/
-export async function rankNpmRegistries(
+export async function probeNpmRegistries(
signal: AbortSignal,
fetcher: typeof fetch = fetch,
probeMs = 4_000,
-): Promise<string[]> {
+): Promise<{ registry: string; bytes: number }[]> {
const registries = [npmRegistry, npmMirrorRegistry];
const window = AbortSignal.any([signal, AbortSignal.timeout(probeMs)]);
// A body that ignores the signal still stops counting when the window ends.
@@ -83,6 +83,5 @@ export async function rankNpmRegistries(
signal.throwIfAborted();
return registries
.map((registry, index) => ({ registry, bytes: received[index]! }))
- .sort((left, right) => right.bytes - left.bytes)
- .map((item) => item.registry);
+ .sort((left, right) => right.bytes - left.bytes);
}
diff --git a/packages/local-installation/src/region.test.ts b/packages/local-installation/src/region.test.ts
new file mode 100644
index 00000000..d3aa9b77
--- /dev/null
+++ b/packages/local-installation/src/region.test.ts
@@ -0,0 +1,224 @@
+import { createHash } from "node:crypto";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { requestUrlText } from "@linger/service-kit";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import {
+ downloadInRegion,
+ forcedRegion,
+ recordRegionFallback,
+ REGION_SCHEMA,
+ regionFile,
+ resolveRegion,
+ type RegionRecord,
+} from "./region.js";
+
+const roots: string[] = [];
+beforeEach(() => vi.stubEnv("SIMPLEX_REGION", ""));
+afterEach(async () => {
+ vi.unstubAllEnvs();
+ for (const root of roots.splice(0))
+ await rm(root, { recursive: true, force: true });
+});
+// Each test has its own home, so the per-process resolution never carries over.
+async function home() {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "linger-region-"));
+ roots.push(directory);
+ return directory;
+}
+const read = async (directory: string) =>
+ JSON.parse(await readFile(regionFile(directory), "utf8")) as RegionRecord;
+async function saved(
+ directory: string,
+ record: Partial<RegionRecord> & Pick<RegionRecord, "region">,
+) {
+ await mkdir(path.dirname(regionFile(directory)), { recursive: true });
+ await writeFile(
+ regionFile(directory),
+ JSON.stringify({
+ schema: REGION_SCHEMA,
+ resolved_at: new Date().toISOString(),
+ method: "probe",
+ ...record,
+ }),
+ );
+}
+// A probe where the China mirror delivers `mirror` bytes and npmjs `global`.
+function probe(mirror: number, global: number) {
+ return vi.fn(async (input: string | URL | Request) => {
+ const host = new URL(requestUrlText(input)).host;
+ const bytes = host === "cdn.npmmirror.com" ? mirror : global;
+ return bytes < 0
+ ? new Response(null, { status: 503 })
+ : new Response(new Uint8Array(bytes));
+ }) as unknown as typeof fetch & ReturnType<typeof vi.fn>;
+}
+const day = 24 * 60 * 60_000;
+
+it("takes SIMPLEX_REGION over a saved region and records it", async () => {
+ const directory = await home();
+ await saved(directory, { region: "global" });
+ vi.stubEnv("SIMPLEX_REGION", "cn");
+ const fetcher = probe(10, 1);
+ expect(await resolveRegion(directory, { fetcher })).toBe("cn");
+ expect(fetcher).not.toHaveBeenCalled();
+ expect(await read(directory)).toMatchObject({
+ schema: "simplex.region/v1",
+ region: "cn",
+ method: "env",
+ });
+});
+
+it("treats auto and unset as not forced and refuses anything else", () => {
+ expect(forcedRegion({})).toBeUndefined();
+ expect(forcedRegion({ SIMPLEX_REGION: "auto" })).toBeUndefined();
+ expect(forcedRegion({ SIMPLEX_REGION: "global" })).toBe("global");
+ expect(() => forcedRegion({ SIMPLEX_REGION: "china" })).toThrow(
+ /auto, global or cn/,
+ );
+});
+
+it("reuses a region saved within 7 days without probing", async () => {
+ const directory = await home();
+ await saved(directory, {
+ region: "cn",
+ method: "fallback",
+ resolved_at: new Date(Date.now() - 6 * day).toISOString(),
+ });
+ const fetcher = probe(1, 10);
+ expect(await resolveRegion(directory, { fetcher })).toBe("cn");
+ expect(fetcher).not.toHaveBeenCalled();
+});
+
+it("probes again once the saved region is stale or unreadable", async () => {
+ for (const contents of [
+ {
+ region: "global",
+ resolved_at: new Date(Date.now() - 8 * day).toISOString(),
+ },
+ { region: "mars" },
+ ] as const) {
+ const directory = await home();
+ await saved(directory, contents as Pick<RegionRecord, "region">);
+ const fetcher = probe(4096, 16);
+ expect(await resolveRegion(directory, { fetcher })).toBe("cn");
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ const record = await read(directory);
+ expect(record).toMatchObject({ region: "cn", method: "probe" });
+ expect(Date.now() - Date.parse(record.resolved_at)).toBeLessThan(60_000);
+ }
+});
+
+it("resolves once per process and home", async () => {
+ const directory = await home();
+ const fetcher = probe(16, 4096);
+ const [first, second] = await Promise.all([
+ resolveRegion(directory, { fetcher }),
+ resolveRegion(directory, { fetcher }),
+ ]);
+ expect([first, second]).toEqual(["global", "global"]);
+ expect(await resolveRegion(directory, { fetcher })).toBe("global");
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ expect(await read(directory)).toMatchObject({
+ region: "global",
+ method: "probe",
+ });
+});
+
+it("stays global without saving when neither registry answers", async () => {
+ const directory = await home();
+ expect(await resolveRegion(directory, { fetcher: probe(-1, -1) })).toBe(
+ "global",
+ );
+ await expect(readFile(regionFile(directory))).rejects.toThrow();
+});
+
+const body = Buffer.from("verified bytes");
+const digest = createHash("sha256").update(body).digest("hex");
+const timing = { attempts: 1, retryDelayMs: 0, idleTimeoutMs: 5_000 };
+const sources = {
+ url: "https://nodejs.org/dist/v1/node.tgz",
+ mirrors: ["https://cdn.npmmirror.com/binaries/node/v1/node.tgz"],
+};
+// Serves the file except from `failing` hosts; records the hosts asked.
+function server(failing: string[] = []) {
+ const hosts: string[] = [];
+ const fetcher = (async (input: string | URL | Request) => {
+ const host = new URL(requestUrlText(input)).host;
+ hosts.push(host);
+ return failing.includes(host)
+ ? new Response(null, { status: 404 })
+ : new Response(body);
+ }) as typeof fetch;
+ return { hosts, fetcher };
+}
+const download = async (
+ directory: string,
+ fetcher: typeof fetch,
+ options: { url: string; mirrors?: string[] } = sources,
+) =>
+ downloadInRegion(
+ directory,
+ {
+ ...options,
+ output: path.join(directory, `download-${Math.random()}`),
+ algorithm: "sha256",
+ digest,
+ maxBytes: 1024,
+ signal: new AbortController().signal,
+ },
+ fetcher,
+ timing,
+ );
+
+it("tries the region's source first and keeps the others", async () => {
+ for (const [region, first] of [
+ ["cn", "cdn.npmmirror.com"],
+ ["global", "nodejs.org"],
+ ] as const) {
+ const directory = await home();
+ await saved(directory, { region });
+ const { hosts, fetcher } = server();
+ expect(await download(directory, fetcher)).toContain(first);
+ expect(hosts).toEqual([first]);
+ }
+});
+
+it("does not resolve a region for a download offered by one region only", async () => {
+ const directory = await home();
+ const { hosts, fetcher } = server();
+ await download(directory, fetcher, {
+ url: "https://cdn.example/a.tgz",
+ mirrors: ["https://mirror.example/a.tgz"],
+ });
+ expect(hosts).toEqual(["cdn.example"]);
+ await expect(readFile(regionFile(directory))).rejects.toThrow();
+});
+
+it("falls back to the other region and records it for later downloads", async () => {
+ const directory = await home();
+ await saved(directory, { region: "cn" });
+ const first = server(["cdn.npmmirror.com"]);
+ expect(await download(directory, first.fetcher)).toContain("nodejs.org");
+ expect(first.hosts).toEqual(["cdn.npmmirror.com", "nodejs.org"]);
+ expect(await read(directory)).toMatchObject({
+ region: "global",
+ method: "fallback",
+ });
+ // The same process now starts from the region that worked.
+ const second = server();
+ await download(directory, second.fetcher);
+ expect(second.hosts).toEqual(["nodejs.org"]);
+ expect(await resolveRegion(directory)).toBe("global");
+});
+
+it("keeps a forced region when a download falls back", async () => {
+ const directory = await home();
+ vi.stubEnv("SIMPLEX_REGION", "cn");
+ const { fetcher } = server(["cdn.npmmirror.com"]);
+ expect(await download(directory, fetcher)).toContain("nodejs.org");
+ expect(await read(directory)).toMatchObject({ region: "cn", method: "env" });
+ await recordRegionFallback(directory, "global");
+ expect(await resolveRegion(directory)).toBe("cn");
+});
diff --git a/packages/local-installation/src/region.ts b/packages/local-installation/src/region.ts
new file mode 100644
index 00000000..32f52600
--- /dev/null
+++ b/packages/local-installation/src/region.ts
@@ -0,0 +1,178 @@
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { orderByRegion, sourceRegion, type Region } from "@linger/service-kit";
+import { downloadVerified, type DownloadTiming } from "./download.js";
+import { npmMirrorRegistry, probeNpmRegistries } from "./npm-registry.js";
+import { atomicPrivate, privateDirectory } from "./private-files.js";
+
+export type { Region };
+
+// The record localmodels shares: see scripts/installs/README.md.
+export const REGION_SCHEMA = "simplex.region/v1";
+const STALE_MS = 7 * 24 * 60 * 60_000;
+export interface RegionRecord {
+ schema: typeof REGION_SCHEMA;
+ region: Region;
+ /** ISO 8601 UTC. */
+ resolved_at: string;
+ method: "env" | "probe" | "fallback";
+}
+
+/** Where a home keeps its resolved download region. */
+export function regionFile(home: string): string {
+ return path.join(path.resolve(home), "runtime", "region.json");
+}
+
+/** SIMPLEX_REGION when it names a region; undefined for `auto` or unset. */
+export function forcedRegion(
+ environment: NodeJS.ProcessEnv = process.env,
+): Region | undefined {
+ const value = environment.SIMPLEX_REGION?.trim() || "auto";
+ if (value === "auto") return undefined;
+ if (value === "cn" || value === "global") return value;
+ throw new Error("SIMPLEX_REGION must be auto, global or cn.");
+}
+
+async function readRecord(file: string): Promise<RegionRecord | undefined> {
+ let value: Partial<RegionRecord>;
+ try {
+ value = JSON.parse(await readFile(file, "utf8")) as Partial<RegionRecord>;
+ } catch {
+ return undefined;
+ }
+ return value?.schema === REGION_SCHEMA &&
+ (value.region === "cn" || value.region === "global") &&
+ (value.method === "env" ||
+ value.method === "probe" ||
+ value.method === "fallback") &&
+ typeof value.resolved_at === "string"
+ ? (value as RegionRecord)
+ : undefined;
+}
+
+function fresh(record: RegionRecord, now: number): boolean {
+ const age = now - Date.parse(record.resolved_at);
+ return age >= 0 && age < STALE_MS;
+}
+
+// The record only saves a later probe; a home that cannot hold it still
+// downloads.
+async function save(
+ file: string,
+ region: Region,
+ method: RegionRecord["method"],
+) {
+ const record: RegionRecord = {
+ schema: REGION_SCHEMA,
+ region,
+ resolved_at: new Date().toISOString(),
+ method,
+ };
+ try {
+ await privateDirectory(path.dirname(file));
+ await atomicPrivate(file, `${JSON.stringify(record)}\n`);
+ } catch {
+ // Best effort, as above.
+ }
+}
+
+// One resolution per home and process, so concurrent downloads share a probe.
+const resolutions = new Map<string, Promise<Region>>();
+
+async function resolve(
+ file: string,
+ signal: AbortSignal,
+ fetcher: typeof fetch,
+): Promise<Region> {
+ const forced = forcedRegion();
+ const saved = await readRecord(file);
+ if (forced) {
+ if (
+ saved?.region !== forced ||
+ saved.method !== "env" ||
+ !fresh(saved, Date.now())
+ )
+ await save(file, forced, "env");
+ return forced;
+ }
+ if (saved && fresh(saved, Date.now())) return saved.region;
+ const [best] = await probeNpmRegistries(signal, fetcher);
+ // Neither registry answered: global for now, probed again next run.
+ if (!best || best.bytes <= 0) return "global";
+ const region = best.registry === npmMirrorRegistry ? "cn" : "global";
+ await save(file, region, "probe");
+ return region;
+}
+
+/**
+ * The download region of `home`: SIMPLEX_REGION when it names one, else a
+ * region.json resolved within the last 7 days, else the npm registry probe
+ * (cn when the China mirror delivers more). Resolved once per process.
+ */
+export function resolveRegion(
+ home: string,
+ options: { signal?: AbortSignal; fetcher?: typeof fetch } = {},
+): Promise<Region> {
+ const file = regionFile(home);
+ let pending = resolutions.get(file);
+ if (!pending) {
+ pending = resolve(
+ file,
+ options.signal ?? new AbortController().signal,
+ options.fetcher ?? fetch,
+ );
+ resolutions.set(file, pending);
+ // An aborted probe leaves nothing behind; the next caller probes again.
+ pending.catch(() => {
+ if (resolutions.get(file) === pending) resolutions.delete(file);
+ });
+ }
+ return pending;
+}
+
+/**
+ * Records that a download fell back to `region` because the preferred one
+ * failed: this process and the next runs prefer it. A region forced through
+ * SIMPLEX_REGION stays forced.
+ */
+export async function recordRegionFallback(
+ home: string,
+ region: Region,
+): Promise<void> {
+ if (forcedRegion()) return;
+ const file = regionFile(home);
+ const current = await resolutions.get(file)?.catch(() => undefined);
+ if (current === region) return;
+ resolutions.set(file, Promise.resolve(region));
+ await save(file, region, "fallback");
+}
+
+/**
+ * downloadVerified with the sources in the home's region first. Only a
+ * download offered by both regions resolves the region, so one served from
+ * a single region never probes. When the other region served it, that
+ * becomes the home's region.
+ */
+export async function downloadInRegion(
+ home: string,
+ options: Parameters<typeof downloadVerified>[0],
+ fetcher: typeof fetch = fetch,
+ timing?: DownloadTiming,
+): Promise<string> {
+ const sources = [options.url, ...(options.mirrors ?? [])];
+ if (new Set(sources.map(sourceRegion)).size < 2)
+ return downloadVerified(options, fetcher, timing);
+ const region = await resolveRegion(home, {
+ signal: options.signal,
+ fetcher,
+ });
+ const [url, ...mirrors] = orderByRegion(region, sources);
+ const served = await downloadVerified(
+ { ...options, url: url!, mirrors },
+ fetcher,
+ timing,
+ );
+ const servedRegion = sourceRegion(served);
+ if (servedRegion !== region) await recordRegionFallback(home, servedRegion);
+ return served;
+}
diff --git a/packages/service-kit/AGENTS.md b/packages/service-kit/AGENTS.md
index 04ee977d..7b41f618 100644
--- a/packages/service-kit/AGENTS.md
+++ b/packages/service-kit/AGENTS.md
@@ -1,6 +1,7 @@
# Service Kit: Shared TypeScript service helpers
-Small helpers shared by Web, Node services, and Voice Runtime.
+Small helpers shared by Web, Node services, Voice Runtime, and the local
+installation core.
## Common Commands
@@ -9,7 +10,9 @@ Small helpers shared by Web, Node services, and Voice Runtime.
## Structure
- `src/index.ts`: isomorphic entry (`isRecord`, `isNodeError`, `asError`,
- `displayText`, `sleep`, fetch test-double text helpers). It must not import
+ `displayText`, `sleep`, fetch test-double text helpers, and `sourceRegion`
+ / `orderByRegion`, which order mirrors of one download by the
+ `SIMPLEX_REGION` contract in `scripts/installs/README.md`). It must not import
`node:` modules because the Web app bundles it.
- `src/node.ts`: Node-only entry (`sha256Hex`, `createJsonLogger`,
`serviceCredential`). `serviceCredential` takes the environment from its
diff --git a/packages/service-kit/src/index.test.ts b/packages/service-kit/src/index.test.ts
index 654dffb6..e3f66cb8 100644
--- a/packages/service-kit/src/index.test.ts
+++ b/packages/service-kit/src/index.test.ts
@@ -5,9 +5,11 @@ import {
displayText,
isNodeError,
isRecord,
+ orderByRegion,
requestBodyText,
requestUrlText,
sleep,
+ sourceRegion,
} from "./index.js";
describe("isRecord", () => {
@@ -92,3 +94,39 @@ describe("request text helpers", () => {
expect(() => requestBodyText(null)).toThrow(TypeError);
});
});
+
+describe("download regions", () => {
+ const sources = [
+ "https://nodejs.org/dist/node.tgz",
+ "https://cdn.npmmirror.com/binaries/node/node.tgz",
+ "https://registry.npmjs.org/a/-/a.tgz",
+ "https://mirrors.aliyun.com/golang/go.tgz",
+ ];
+
+ it("knows the mainland-China mirrors", () => {
+ expect(sources.map(sourceRegion)).toEqual(["global", "cn", "global", "cn"]);
+ expect(sourceRegion("https://goproxy.cn")).toBe("cn");
+ expect(sourceRegion("https://npmmirror.com.example/x")).toBe("global");
+ expect(sourceRegion("not a url")).toBe("global");
+ });
+
+ it("puts the region's sources first and keeps every source", () => {
+ expect(orderByRegion("cn", sources)).toEqual([
+ sources[1],
+ sources[3],
+ sources[0],
+ sources[2],
+ ]);
+ expect(orderByRegion("global", sources)).toEqual([
+ sources[0],
+ sources[2],
+ sources[1],
+ sources[3],
+ ]);
+ // A list already global-first is unchanged for global.
+ expect(orderByRegion("global", [sources[0]!, sources[1]!])).toEqual([
+ sources[0],
+ sources[1],
+ ]);
+ });
+});
diff --git a/packages/service-kit/src/index.ts b/packages/service-kit/src/index.ts
index 9c88dd63..e5749ac9 100644
--- a/packages/service-kit/src/index.ts
+++ b/packages/service-kit/src/index.ts
@@ -72,3 +72,38 @@ export const requestBodyText = (body: unknown): string => {
}
return body;
};
+
+/** Where a download source serves from: a mainland-China mirror, or anywhere else. */
+export type Region = "cn" | "global";
+
+// Hosts that mirror public downloads inside mainland China.
+const chinaMirrorDomains = ["npmmirror.com", "aliyun.com", "goproxy.cn"];
+
+/** The region of a download source's host; an unparsable URL counts as global. */
+export function sourceRegion(source: string | URL): Region {
+ let host: string;
+ try {
+ host = new URL(source).hostname;
+ } catch {
+ return "global";
+ }
+ return chinaMirrorDomains.some(
+ (domain) => host === domain || host.endsWith(`.${domain}`),
+ )
+ ? "cn"
+ : "global";
+}
+
+/**
+ * Sources of the same bytes with those in `region` first. Each region keeps
+ * its listed order, and no source is dropped.
+ */
+export function orderByRegion<T extends string | URL>(
+ region: Region,
+ sources: readonly T[],
+): T[] {
+ return [
+ ...sources.filter((source) => sourceRegion(source) === region),
+ ...sources.filter((source) => sourceRegion(source) !== region),
+ ];
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3d76f889..418d6762 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -730,6 +730,9 @@ importers:
packages/local-installation:
dependencies:
+ '@linger/service-kit':
+ specifier: workspace:*
+ version: link:../service-kit
tar:
specifier: 7.5.22
version: 7.5.22
diff --git a/scripts/env-inventory.json b/scripts/env-inventory.json
index f397355c..d384f6e9 100644
--- a/scripts/env-inventory.json
+++ b/scripts/env-inventory.json
@@ -108,7 +108,7 @@
},
"installer": {
"owner": "out-of-env",
- "description": "Read by the local installer and @linger/local-installation on user machines: the installer home, the local models tool, the app model gateway passed to natively started services, a package registry and Go module proxy the person configured for native source, and Python variables cleared before running it. Not part of .env.",
+ "description": "Read by the local installer and @linger/local-installation on user machines: the installer home, the local models tool, the app model gateway passed to natively started services, a package registry and Go module proxy the person configured for native source, the download region (SIMPLEX_REGION: cn, global or auto; the installer passes the resolved one to node-services and localmodels, see scripts/installs/README.md), and Python variables cleared before running it. Not part of .env.",
"names": [
"GOPROXY",
"LOCAL_ENV_FILE",
@@ -123,7 +123,8 @@
"LINGER_LOCALMODELS_DEV_PYTHON",
"LINGER_LOCALMODELS_TOOL_JSON",
"LINGER_NATIVE_DEPENDENCIES_JSON",
- "LINGER_NATIVE_VOICE_TOOLS_JSON"
+ "LINGER_NATIVE_VOICE_TOOLS_JSON",
+ "SIMPLEX_REGION"
]
},
"voice-workers": {
diff --git a/scripts/installs/README.md b/scripts/installs/README.md
index 496315ae..374e1357 100644
--- a/scripts/installs/README.md
+++ b/scripts/installs/README.md
@@ -106,3 +106,49 @@ and this section carry that release's pin; do not edit them by hand. The version
runs; it does not state which platforms or GPUs are supported.
<!-- <<< llm-inference-lab: stack -->
+
+## Download region: `SIMPLEX_REGION` and `region.json`
+
+Linger and localmodels share one download region, so a computer in mainland
+China gets the China mirrors without first waiting for a foreign host to time
+out. The region only orders the sources of a download: no source is ever
+dropped, and the pinned SHA256, SHA512 or lockfile integrity still decides
+which bytes are used.
+
+The installer resolves the region once per process, in this order:
+
+1. `SIMPLEX_REGION`: `cn` or `global` forces that region; `auto` or unset
+ does not. Any other value is an error.
+2. `<LINGER_HOME>/runtime/region.json` when it was resolved within the last
+ 7 days.
+3. A probe: the pinned pnpm tarball from `registry.npmjs.org` and from
+ `cdn.npmmirror.com` for 4 seconds; `cn` when the China mirror delivers
+ more. A probe that reaches neither uses `global` and is not saved.
+
+```json
+{
+ "schema": "simplex.region/v1",
+ "region": "cn",
+ "resolved_at": "2026-11-18T08:00:00.000Z",
+ "method": "probe"
+}
+```
+
+`method` is `env`, `probe` or `fallback`. When every source of the preferred
+region fails and the other region serves the download, the file is rewritten
+with that region and `fallback`, and later downloads start there (unless
+`SIMPLEX_REGION` forces a region).
+
+| Download | global first | cn first |
+| ------------------------------------ | -------------------- | ---------------------------------------- |
+| Node.js runtime (desktop app) | `nodejs.org` | `cdn.npmmirror.com` |
+| pnpm, npm and package installs | `registry.npmjs.org` | `registry.npmmirror.com` |
+| Go toolchain | `dl.google.com` | `mirrors.aliyun.com` |
+| Go modules (`GOPROXY`, unless set) | `proxy.golang.org` | `goproxy.cn` |
+| localmodels kit | CloudFront, then npm | `cdn.npmmirror.com` where it has the kit |
+| Voice model packages (node-services) | `registry.npmjs.org` | `registry.npmmirror.com` |
+
+A registry or `GOPROXY` the person configured still wins. The installer
+passes the resolved region as `SIMPLEX_REGION` to every `localmodels` child
+(stack, foundations, Harness) and to every native service, so none of them
+probes again.
diff --git a/scripts/local-computer-node-distributions.mjs b/scripts/local-computer-node-distributions.mjs
index a8258e89..a6e7bf84 100644
--- a/scripts/local-computer-node-distributions.mjs
+++ b/scripts/local-computer-node-distributions.mjs
@@ -40,13 +40,14 @@ export const RELEASE_TARGETS = Object.freeze(
);
export const NODE_RUNTIME_DOWNLOAD_BASE_URL = "https://nodejs.org/dist";
// Serves the same archives, so the pinned checksums still decide what is
-// used; tried when nodejs.org is unreachable or slow.
+// used; tried when nodejs.org is unreachable or slow. The desktop app tries it
+// first in the cn download region (scripts/installs/README.md).
export const NODE_RUNTIME_DOWNLOAD_MIRRORS = Object.freeze([
"https://cdn.npmmirror.com/binaries/node",
]);
const NODE_RUNTIME_IDLE_TIMEOUT_MS = 60_000;
-/** Every host for one pinned archive, the official one first. */
+/** Every host for one pinned archive, the official one first; the desktop app orders them by region. */
export function nodeRuntimeDownloadUrls(
archive,
version = NODE_RUNTIME_VERSION,