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): record the localmodels tool in the Computer config

Dongdong Chenfb7237b733bc
diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md
index 5ab63538..0b8779f7 100644
--- a/packages/local-installation/AGENTS.md
+++ b/packages/local-installation/AGENTS.md
@@ -74,6 +74,14 @@ fresh cluster and logs where the data went. The desktop finds the newest backup
after the job, enrolls its Computer again once (the old Computer ID is
unknown to the fresh database) and shows the folder on its ready screen.
+The Computer config's `local_models` section names the verified localmodels
+tool, its `LOCALMODELS_STATE` and model base directory for the Daemon's model
+library (`localmodels-computer.ts`). A fresh login passes it as
+`--localmodels-*` options; it is part of the managed-runtime fingerprint, so an
+existing Computer is rebound once on its next connect. A distribution without
+the tool writes none. External Computers (the Desktop's) get the same paths as
+the `LINGER_LOCALMODELS_*` keys of the installer's instance runtime.
+
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/src/computer-current-cli.test.ts b/packages/local-installation/src/computer-current-cli.test.ts
index 1c250fea..6d806143 100644
--- a/packages/local-installation/src/computer-current-cli.test.ts
+++ b/packages/local-installation/src/computer-current-cli.test.ts
@@ -7,6 +7,8 @@ import { writeSetupChoice } from "./setup-selection.js";
import { connectComputer, inspectComputer, stopComputer } from "./computer.js";
vi.mock("./localmodels-tool.js", () => ({
+ // This distribution ships no localmodels tool.
+ pinnedToolSource: () => undefined,
runLocalmodels: async () => ({
code: 0,
stderr: "",
diff --git a/packages/local-installation/src/computer-selection.test.ts b/packages/local-installation/src/computer-selection.test.ts
index dc685a9a..a5746146 100644
--- a/packages/local-installation/src/computer-selection.test.ts
+++ b/packages/local-installation/src/computer-selection.test.ts
@@ -6,7 +6,11 @@ import { initializeInstance } from "./instance.js";
import { writeSetupChoice } from "./setup-selection.js";
import { connectComputer } from "./computer.js";
import { runLocalmodels } from "./localmodels-tool.js";
-vi.mock("./localmodels-tool.js", () => ({ runLocalmodels: vi.fn() }));
+vi.mock("./localmodels-tool.js", () => ({
+ // This distribution ships no localmodels tool.
+ pinnedToolSource: () => undefined,
+ runLocalmodels: vi.fn(),
+}));
const roots: string[] = [];
afterEach(async () => {
vi.unstubAllEnvs();
diff --git a/packages/local-installation/src/computer-start-race.test.ts b/packages/local-installation/src/computer-start-race.test.ts
index 9ec4c269..eff37d99 100644
--- a/packages/local-installation/src/computer-start-race.test.ts
+++ b/packages/local-installation/src/computer-start-race.test.ts
@@ -6,6 +6,8 @@ import { initializeInstance } from "./instance.js";
import { writeSetupChoice } from "./setup-selection.js";
import { connectComputer } from "./computer.js";
vi.mock("./localmodels-tool.js", () => ({
+ // This distribution ships no localmodels tool.
+ pinnedToolSource: () => undefined,
runLocalmodels: async () => ({
code: 0,
stderr: "",
diff --git a/packages/local-installation/src/computer.test.ts b/packages/local-installation/src/computer.test.ts
index a4c1c07f..c37541cc 100644
--- a/packages/local-installation/src/computer.test.ts
+++ b/packages/local-installation/src/computer.test.ts
@@ -29,6 +29,18 @@ function managedCodexPath(home: string) {
return managedNativeRuntimePath(home, "codex");
}
vi.mock("./localmodels-tool.js", () => ({
+ // The distribution ships a tool when the test stubs its metadata.
+ pinnedToolSource: () =>
+ process.env.LINGER_LOCALMODELS_TOOL_JSON ? { sha256: "0" } : undefined,
+ ensureLocalmodelsTool: async (home: string) => ({
+ python: path.join(home, "tools", "localmodels", "kit", "python3"),
+ moduleDir: path.join(home, "tools", "localmodels", "kit"),
+ sourceCommit: "0".repeat(40),
+ }),
+ localmodelsStateDirectory: (home: string) =>
+ path.join(home, "runtime", "localmodels", "state"),
+ localmodelsBaseDirectory: (home: string) =>
+ path.join(home, "runtime", "localmodels", "models"),
runLocalmodels: async (
home: string,
args: string[],
@@ -1313,3 +1325,92 @@ it("keeps a genuine failed start actionable only after bounded offline observati
),
).toHaveLength(1);
});
+
+function localModelsTool(home: string) {
+ return {
+ python: path.join(home, "tools", "localmodels", "kit", "python3"),
+ module_directory: path.join(home, "tools", "localmodels", "kit"),
+ state_directory: path.join(home, "runtime", "localmodels", "state"),
+ base_directory: path.join(home, "runtime", "localmodels", "models"),
+ };
+}
+function connectedStatus(args: string[]) {
+ return args.slice(0, 2).join(" ") === "daemon status"
+ ? JSON.stringify({
+ daemon: {
+ state: "running",
+ reconciled: true,
+ gateway_state: "connected",
+ active_operations: 0,
+ },
+ runtimes: [{ type: "codex", status: "ready" }],
+ })
+ : "";
+}
+it("names the localmodels tool when login creates the Computer config", async () => {
+ vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", "{}");
+ try {
+ const f = await fixture();
+ const home = path.resolve(f.instance.root, "../..");
+ const run = vi
+ .spyOn(processes, "runProcess")
+ .mockImplementation(async (_executable, args) => {
+ if (args[0] === "login")
+ await writeFile(f.instance.computerConfig, "{}");
+ return { code: 0, stderr: "", stdout: connectedStatus(args) };
+ });
+ await connectComputer(f.instance, { interactive: true });
+ const login = run.mock.calls.find(([, args]) => args[0] === "login")![1];
+ const tool = localModelsTool(home);
+ for (const [flag, value] of [
+ ["--localmodels-python", tool.python],
+ ["--localmodels-module-dir", tool.module_directory],
+ ["--localmodels-state", tool.state_directory],
+ ["--localmodels-base-dir", tool.base_directory],
+ ] as const)
+ expect(login[login.indexOf(flag) + 1]).toBe(value);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+});
+it("adds the localmodels tool to an existing Computer config once", async () => {
+ const f = await fixture();
+ const home = path.resolve(f.instance.root, "../..");
+ await writeFile(
+ f.instance.computerConfig,
+ JSON.stringify({
+ runner_id: "same-identity",
+ runtime_paths: { codex: "/existing/codex" },
+ }),
+ { mode: 0o600 },
+ );
+ const run = vi
+ .spyOn(processes, "runProcess")
+ .mockImplementation(async (_executable, args) => ({
+ code: 0,
+ stderr: "",
+ stdout: connectedStatus(args),
+ }));
+ const stops = () =>
+ run.mock.calls.filter(
+ ([, args]) => args.slice(0, 2).join(" ") === "daemon stop",
+ ).length;
+ // A Computer bound before it knew the tool.
+ await connectComputer(f.instance, { interactive: false });
+ await connectComputer(f.instance, { interactive: false });
+ expect(stops()).toBe(1);
+ vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", "{}");
+ try {
+ await connectComputer(f.instance, { interactive: false });
+ await connectComputer(f.instance, { interactive: false });
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ expect(stops()).toBe(2);
+ const config = JSON.parse(await readFile(f.instance.computerConfig, "utf8"));
+ expect(config).toEqual({
+ runner_id: "same-identity",
+ runtime_paths: { codex: "/existing/codex" },
+ local_models: localModelsTool(home),
+ });
+});
diff --git a/packages/local-installation/src/computer.ts b/packages/local-installation/src/computer.ts
index 9f42d1ff..e9a8ff7f 100644
--- a/packages/local-installation/src/computer.ts
+++ b/packages/local-installation/src/computer.ts
@@ -6,6 +6,13 @@ import { atomicPrivate, readPrivate, type Instance } from "./instance.js";
import { runProcess } from "./process.js";
import path from "node:path";
import { localModelsEnvironment } from "./local-models.js";
+import {
+ localModelsConfig,
+ localModelsLoginArguments,
+ localmodelsComputerTool,
+ type LocalmodelsComputerTool,
+} from "./localmodels-computer.js";
+import { pinnedToolSource } from "./localmodels-tool.js";
import {
inspectSelectedRuntimeDescriptors,
runtimeEnvironmentFromDescriptors,
@@ -225,10 +232,17 @@ async function managedRuntimeState(instance: Instance) {
const managed = runtimeEnvironmentFromDescriptors(descriptors);
Object.assign(managed, await localModelsEnvironment(instance));
managed.PATH = await runtimePath(instance);
+ // Part of the fingerprint, so an install from before the Computer knew
+ // its localmodels tool is rebound once on its next connect.
+ const localModels = await localmodelsComputerTool(
+ path.resolve(instance.root, "../.."),
+ pinnedToolSource(),
+ );
const fingerprint = createHash("sha256")
.update(
JSON.stringify({
managed,
+ localModels,
revisions: descriptors.map((row) => ({
runtime: row.runtime,
revision: row.configFingerprint,
@@ -239,6 +253,7 @@ async function managedRuntimeState(instance: Instance) {
.digest("hex");
return {
managed,
+ localModels,
fingerprint,
authFile: descriptors.find((row) => row.runtime === "codex")?.computer
?.authFile,
@@ -252,14 +267,15 @@ async function bindManagedRuntime(
instance: Instance,
managed: NodeJS.ProcessEnv,
authFile?: string,
+ localModels?: LocalmodelsComputerTool,
) {
- if (
- !managed.CODEX_HOME &&
- !managed.LINGER_CODEX_PATH &&
- !managed.LINGER_CLAUDE_PATH &&
- !managed.LINGER_PI_PATH
- )
- return;
+ const runtime = Boolean(
+ managed.CODEX_HOME ||
+ managed.LINGER_CODEX_PATH ||
+ managed.LINGER_CLAUDE_PATH ||
+ managed.LINGER_PI_PATH,
+ );
+ if (!runtime && !localModels) return;
const contents = await readPrivate(instance.computerConfig);
if (!contents) throw new Error("Instance Computer configuration is missing");
const parsed: unknown = JSON.parse(contents);
@@ -274,17 +290,20 @@ async function bindManagedRuntime(
Array.isArray(config[key]))
)
throw new Error("Invalid instance Computer runtime configuration");
- if (authFile) {
- if (!path.isAbsolute(authFile))
- throw new Error("Invalid upstream Computer credential binding");
- config.codex = { ...record(config.codex), auth_file: authFile };
+ if (runtime) {
+ if (authFile) {
+ if (!path.isAbsolute(authFile))
+ throw new Error("Invalid upstream Computer credential binding");
+ config.codex = { ...record(config.codex), auth_file: authFile };
+ }
+ config.runtime_paths = Object.fromEntries(
+ (["codex", "claude", "pi"] as const).flatMap((name) => {
+ const executable = managed[`LINGER_${name.toUpperCase()}_PATH`];
+ return executable ? [[name, executable]] : [];
+ }),
+ );
}
- config.runtime_paths = Object.fromEntries(
- (["codex", "claude", "pi"] as const).flatMap((runtime) => {
- const executable = managed[`LINGER_${runtime.toUpperCase()}_PATH`];
- return executable ? [[runtime, executable]] : [];
- }),
- );
+ if (localModels) config.local_models = localModelsConfig(localModels);
await atomicPrivate(
instance.computerConfig,
JSON.stringify(config, null, 2) + "\n",
@@ -323,6 +342,7 @@ async function connectInstanceComputer(
desired.managed[`LINGER_${runtime.toUpperCase()}_PATH`];
return executable ? [`--${runtime}-path`, executable] : [];
}),
+ ...localModelsLoginArguments(desired.localModels),
],
options.signal,
10 * 60_000,
@@ -352,7 +372,9 @@ async function connectInstanceComputer(
const refresh =
!startedByLogin &&
receipt !== desired.fingerprint &&
- (Boolean(receipt) || Object.keys(desired.managed).length > 0);
+ (Boolean(receipt) ||
+ Object.keys(desired.managed).length > 0 ||
+ desired.localModels !== undefined);
if (refresh) {
if (observed.activeOperations !== 0)
return {
@@ -374,7 +396,12 @@ async function connectInstanceComputer(
detail:
"The instance Computer could not stop safely. Check its active operations and retry.",
};
- await bindManagedRuntime(instance, desired.managed, desired.authFile);
+ await bindManagedRuntime(
+ instance,
+ desired.managed,
+ desired.authFile,
+ desired.localModels,
+ );
// The existing identity and credential references stay in the same instance configuration.
observed = { ...observed, state: "offline", connected: false };
}
diff --git a/packages/local-installation/src/localmodels-computer.test.ts b/packages/local-installation/src/localmodels-computer.test.ts
new file mode 100644
index 00000000..06b21005
--- /dev/null
+++ b/packages/local-installation/src/localmodels-computer.test.ts
@@ -0,0 +1,93 @@
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { afterEach, expect, it, vi } from "vitest";
+import {
+ localModelsConfig,
+ localmodelsComputerTool,
+ localmodelsToolEnvironment,
+ localmodelsToolFromEnvironment,
+} from "./localmodels-computer.js";
+import type { LocalmodelsToolSource } from "./localmodels-tool.js";
+
+const tool = {
+ python: "/home/u/.linger/tools/localmodels/abc/python/bin/python3",
+ moduleDirectory: "/home/u/.linger/tools/localmodels/abc",
+ stateDirectory: "/home/u/.linger/runtime/localmodels/state",
+ baseDirectory: "/home/u/.linger/runtime/localmodels/models",
+};
+
+it("carries the tool through an external Computer's runtime environment", () => {
+ const environment = localmodelsToolEnvironment(tool);
+ expect(
+ Object.keys(environment).every((key) => key.startsWith("LINGER_")),
+ ).toBe(true);
+ expect(localmodelsToolFromEnvironment(environment, path.posix)).toEqual(tool);
+ expect(localModelsConfig(tool)).toEqual({
+ python: tool.python,
+ module_directory: tool.moduleDirectory,
+ state_directory: tool.stateDirectory,
+ base_directory: tool.baseDirectory,
+ });
+});
+
+it("names no tool unless all four paths are absolute", () => {
+ const environment = localmodelsToolEnvironment(tool);
+ expect(localmodelsToolEnvironment(undefined)).toEqual({});
+ expect(localmodelsToolFromEnvironment(undefined)).toBeUndefined();
+ expect(
+ localmodelsToolFromEnvironment(
+ { ...environment, LINGER_LOCALMODELS_STATE: "state" },
+ path.posix,
+ ),
+ ).toBeUndefined();
+ const { LINGER_LOCALMODELS_BASE_DIR: _base, ...partial } = environment;
+ expect(localmodelsToolFromEnvironment(partial, path.posix)).toBeUndefined();
+});
+
+const ensure = vi.hoisted(() => vi.fn());
+vi.mock("./localmodels-tool.js", () => ({
+ ensureLocalmodelsTool: ensure,
+ localmodelsStateDirectory: (home: string) =>
+ path.join(home, "runtime", "localmodels", "state"),
+ localmodelsBaseDirectory: (home: string) =>
+ path.join(home, "runtime", "localmodels", "models"),
+}));
+
+const homes: string[] = [];
+afterEach(async () => {
+ vi.unstubAllEnvs();
+ ensure.mockReset();
+ await Promise.all(
+ homes.splice(0).map((home) => rm(home, { recursive: true, force: true })),
+ );
+});
+
+async function home() {
+ const value = await mkdtemp(path.join(tmpdir(), "localmodels-computer-"));
+ homes.push(value);
+ return value;
+}
+
+it("follows the tool source its caller passes, not the process environment", async () => {
+ vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", '{"sha256":"ambient"}');
+ expect(await localmodelsComputerTool(await home(), undefined)).toBe(
+ undefined,
+ );
+ expect(ensure).not.toHaveBeenCalled();
+
+ vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", "");
+ const source = { sha256: "shipped" } as LocalmodelsToolSource;
+ const where = await home();
+ ensure.mockResolvedValue({
+ python: path.join(where, "kit", "python3"),
+ moduleDir: path.join(where, "kit"),
+ });
+ expect(await localmodelsComputerTool(where, source)).toEqual({
+ python: path.join(where, "kit", "python3"),
+ moduleDirectory: path.join(where, "kit"),
+ stateDirectory: path.join(where, "runtime", "localmodels", "state"),
+ baseDirectory: path.join(where, "runtime", "localmodels", "models"),
+ });
+ expect(ensure).toHaveBeenCalledWith(where, {}, { source });
+});
diff --git a/packages/local-installation/src/localmodels-computer.ts b/packages/local-installation/src/localmodels-computer.ts
new file mode 100644
index 00000000..d61d7189
--- /dev/null
+++ b/packages/local-installation/src/localmodels-computer.ts
@@ -0,0 +1,116 @@
+import path from "node:path";
+import { privateDirectory } from "./instance.js";
+import {
+ ensureLocalmodelsTool,
+ localmodelsBaseDirectory,
+ localmodelsStateDirectory,
+ type LocalmodelsToolSource,
+} from "./localmodels-tool.js";
+
+/**
+ * Where a Computer's Daemon finds the localmodels tool to run the model
+ * library: the config's `local_models` section (computerconfig.LocalModels).
+ * The Daemon runs `<python> -P -s -m localmodels library ...` with
+ * PYTHONPATH and its working directory at moduleDirectory,
+ * LOCALMODELS_STATE at stateDirectory and --base-dir baseDirectory, the
+ * same state and models every installer call uses.
+ */
+export interface LocalmodelsComputerTool {
+ python: string;
+ moduleDirectory: string;
+ stateDirectory: string;
+ baseDirectory: string;
+}
+
+/**
+ * The verified tool of `source`, the tool the caller's distribution ships,
+ * or undefined when it ships none: such a Computer reports
+ * TOOL_NOT_INSTALLED.
+ */
+export async function localmodelsComputerTool(
+ home: string,
+ source: LocalmodelsToolSource | undefined,
+ options: { signal?: AbortSignal } = {},
+): Promise<LocalmodelsComputerTool | undefined> {
+ if (!source) return undefined;
+ const tool = await ensureLocalmodelsTool(home, options, { source });
+ const stateDirectory = localmodelsStateDirectory(home);
+ const baseDirectory = localmodelsBaseDirectory(home);
+ await privateDirectory(stateDirectory);
+ await privateDirectory(baseDirectory);
+ return {
+ python: tool.python,
+ moduleDirectory: tool.moduleDir,
+ stateDirectory,
+ baseDirectory,
+ };
+}
+
+// How the installer's InstanceRuntime environment names the tool for an
+// external Computer such as the Desktop's.
+const ENVIRONMENT = {
+ python: "LINGER_LOCALMODELS_PYTHON",
+ moduleDirectory: "LINGER_LOCALMODELS_MODULE_DIR",
+ stateDirectory: "LINGER_LOCALMODELS_STATE",
+ baseDirectory: "LINGER_LOCALMODELS_BASE_DIR",
+} as const satisfies Record<keyof LocalmodelsComputerTool, string>;
+
+export const LOCALMODELS_TOOL_ENVIRONMENT: readonly string[] =
+ Object.values(ENVIRONMENT);
+
+export function localmodelsToolEnvironment(
+ tool: LocalmodelsComputerTool | undefined,
+): Record<string, string> {
+ if (!tool) return {};
+ return Object.fromEntries(
+ Object.entries(ENVIRONMENT).map(([key, name]) => [
+ name,
+ tool[key as keyof LocalmodelsComputerTool],
+ ]),
+ );
+}
+
+/** The tool an environment names, when it names all four absolute paths. */
+export function localmodelsToolFromEnvironment(
+ environment: Readonly<Record<string, string | undefined>> | undefined,
+ platformPath: typeof path = path,
+): LocalmodelsComputerTool | undefined {
+ const entries = Object.entries(ENVIRONMENT).map(
+ ([key, name]) => [key, environment?.[name]] as const,
+ );
+ if (
+ !entries.every(
+ ([, value]) =>
+ typeof value === "string" && platformPath.isAbsolute(value),
+ )
+ )
+ return undefined;
+ return Object.fromEntries(entries) as unknown as LocalmodelsComputerTool;
+}
+
+/** The Computer config's `local_models` section. */
+export function localModelsConfig(tool: LocalmodelsComputerTool) {
+ return {
+ python: tool.python,
+ module_directory: tool.moduleDirectory,
+ state_directory: tool.stateDirectory,
+ base_directory: tool.baseDirectory,
+ };
+}
+
+/** The `linger-computer login` options that write the same section. */
+export function localModelsLoginArguments(
+ tool: LocalmodelsComputerTool | undefined,
+): string[] {
+ if (!tool) return [];
+ return [
+ "--localmodels-python",
+ tool.python,
+ "--localmodels-module-dir",
+ tool.moduleDirectory,
+ "--localmodels-state",
+ tool.stateDirectory,
+ "--localmodels-base-dir",
+ tool.baseDirectory,
+ ];
+}
diff --git a/packages/local-installation/src/localmodels-tool.ts b/packages/local-installation/src/localmodels-tool.ts
index cd1fa8fe..61cf743a 100644
--- a/packages/local-installation/src/localmodels-tool.ts
+++ b/packages/local-installation/src/localmodels-tool.ts
@@ -405,6 +405,14 @@ export async function ensureLocalmodelsTool(
preparing.delete(key);
}
}
+/** LOCALMODELS_STATE of every call for this home. */
+export function localmodelsStateDirectory(home: string): string {
+ return path.join(path.resolve(home), "runtime", "localmodels", "state");
+}
+/** Where this home's models live: every call's --base-dir. */
+export function localmodelsBaseDirectory(home: string): string {
+ return path.join(path.resolve(home), "runtime", "localmodels", "models");
+}
export async function runLocalmodels(
home: string,
args: string[],
@@ -414,12 +422,7 @@ export async function runLocalmodels(
const startedAt = Date.now();
const tool = await ensureLocalmodelsTool(home, options);
const checkedAt = Date.now();
- const state = path.join(
- path.resolve(home),
- "runtime",
- "localmodels",
- "state",
- );
+ const state = localmodelsStateDirectory(home);
await privateDirectory(state);
const env: NodeJS.ProcessEnv = {
...process.env,
@@ -566,8 +569,12 @@ async function hasPinnedTool(home: string): Promise<boolean> {
() => undefined,
));
}
-/** The kit this release pins, from the installer's published metadata. */
-function pinnedToolSource(): LocalmodelsToolSource | undefined {
+/**
+ * The kit this release pins, from the installer's published metadata
+ * (LINGER_LOCALMODELS_TOOL_JSON), or undefined when it ships none. The one
+ * reader of that variable.
+ */
+export function pinnedToolSource(): LocalmodelsToolSource | undefined {
if (configuredDevTool()) {
return {
url: "https://dev.invalid/localmodels.tgz",