@otto-code/brain 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,5 +17,6 @@ export declare function runRuntimeListCommand(_options: unknown, _command: Comma
17
17
  export declare function addRuntimeInstallOptions(cmd: Command): Command;
18
18
  export declare function runRuntimeInstallCommand(options: {
19
19
  build?: string;
20
+ variant?: string;
20
21
  }, _command: Command): Promise<AnyCommandResult<RuntimeRow>>;
21
22
  //# sourceMappingURL=runtime.d.ts.map
@@ -1,6 +1,7 @@
1
1
  import { loadBrainConfig } from "../config/index.js";
2
2
  import { resolveBrainPaths } from "../config/paths.js";
3
- import { defaultRuntimeSpec, installManagedRuntime, listAllRuntimes } from "../runtime/index.js";
3
+ import { CommandError } from "../output/types.js";
4
+ import { defaultRuntimeSpec, installManagedRuntime, listAllRuntimes, listRuntimeDevices, probeNvidiaGpu, supportedVariants, } from "../runtime/index.js";
4
5
  const runtimeSchema = {
5
6
  idField: "dir",
6
7
  columns: [
@@ -32,12 +33,26 @@ export async function runRuntimeListCommand(_options, _command) {
32
33
  export function addRuntimeInstallOptions(cmd) {
33
34
  return cmd
34
35
  .description("Download a self-contained llama.cpp runtime")
35
- .option("--build <tag>", "llama.cpp release build tag");
36
+ .option("--build <tag>", "llama.cpp release build tag")
37
+ .option("--variant <name>", `accelerator to install (${supportedVariants().join("|")}); defaults to the best one this machine can use`);
36
38
  }
37
39
  export async function runRuntimeInstallCommand(options, _command) {
38
40
  loadBrainConfig();
39
41
  const { runtimesDir } = resolveBrainPaths();
40
- const spec = defaultRuntimeSpec(options.build);
42
+ const available = supportedVariants();
43
+ if (options.variant && !available.includes(options.variant)) {
44
+ throw new CommandError({
45
+ code: "UNSUPPORTED_VARIANT",
46
+ message: `llama.cpp publishes no "${options.variant}" build for ${process.platform}/${process.arch}` +
47
+ ` - available: ${available.join(", ") || "(none)"}`,
48
+ });
49
+ }
50
+ // Only "auto" needs the GPU probe, and only to choose between CUDA and Vulkan
51
+ // on the platforms that have both.
52
+ const spec = defaultRuntimeSpec(options.build, {
53
+ variant: options.variant ?? "auto",
54
+ hasNvidiaGpu: options.variant ? undefined : await probeNvidiaGpu(),
55
+ });
41
56
  process.stderr.write(` installing ${spec.label} (${spec.version})…\n`);
42
57
  const runtime = await installManagedRuntime(spec, runtimesDir, (p) => {
43
58
  if (p.phase === "downloading" && p.totalBytes) {
@@ -48,6 +63,20 @@ export async function runRuntimeInstallCommand(options, _command) {
48
63
  process.stderr.write("\n extracting…\n");
49
64
  });
50
65
  process.stderr.write("\n");
66
+ // A GPU variant that finds no device still runs - on the CPU, at roughly a
67
+ // fortieth of the prefill throughput, and says nothing about it. Measured on
68
+ // WSL2, which carries no NVIDIA Vulkan ICD. Warn rather than fail: the runtime
69
+ // is genuinely installed and usable, just not accelerated.
70
+ // One line on purpose. The daemon's BrainOpsManager keeps the *last* stderr line
71
+ // as the job's message, so a multi-line warning would surface in the UI as a
72
+ // dangling fragment. As one line it survives intact on both the CLI and the GUI.
73
+ if (spec.variant !== "cpu") {
74
+ const devices = await listRuntimeDevices(runtime);
75
+ if (devices.length === 0) {
76
+ process.stderr.write(` warning: this ${spec.variant} runtime reports no GPU device, so inference will run` +
77
+ ` on the CPU until a working ${spec.variant} driver for this GPU is installed.\n`);
78
+ }
79
+ }
51
80
  return {
52
81
  type: "single",
53
82
  data: {
@@ -4,11 +4,13 @@ export interface BrainPaths {
4
4
  configFile: string;
5
5
  profilesFile: string;
6
6
  catalogFile: string;
7
+ renameMapFile: string;
7
8
  modelsDir: string;
8
9
  runtimesDir: string;
9
10
  pidFile: string;
10
11
  activityFile: string;
11
12
  logFile: string;
13
+ logsDir: string;
12
14
  resultsDir: string;
13
15
  }
14
16
  export declare function resolveBrainPaths(env?: NodeJS.ProcessEnv): BrainPaths;
@@ -15,6 +15,7 @@ export function resolveBrainPaths(env = process.env) {
15
15
  configFile: path.join(root, "config.json"),
16
16
  profilesFile: path.join(root, "profiles.json"),
17
17
  catalogFile: path.join(root, "catalog.json"),
18
+ renameMapFile: path.join(root, "rename-map.json"),
18
19
  modelsDir: path.join(root, "models"),
19
20
  runtimesDir: path.join(root, "runtimes"),
20
21
  pidFile: path.join(root, "otto-brain.pid"),
@@ -23,6 +24,7 @@ export function resolveBrainPaths(env = process.env) {
23
24
  // service - which is what answers /__host/status - never sees them otherwise.
24
25
  activityFile: path.join(root, "otto-brain.activity"),
25
26
  logFile: path.join(root, "otto-brain.log"),
27
+ logsDir: path.join(root, "logs"),
26
28
  resultsDir: path.join(root, "results"),
27
29
  };
28
30
  }
@@ -4,6 +4,7 @@ import { CatalogSchema } from "../config/schema.js";
4
4
  import { loadCatalog } from "../config/store.js";
5
5
  import { resolveModelsDirs } from "./dirs.js";
6
6
  import { enrichWithCatalog } from "./enrich.js";
7
+ import { loadRenameMap } from "./rename-map.js";
7
8
  import { scan } from "./scan.js";
8
9
  export * from "./scan.js";
9
10
  export { pickModel, pickAutoModel } from "./pick.js";
@@ -30,6 +31,12 @@ export function scanModels(config, env = process.env, options = {}) {
30
31
  }
31
32
  }
32
33
  const enriched = enrichWithCatalog(all, loadCatalogSafe(env));
34
+ const renameMap = loadRenameMap(resolveBrainPaths(env));
35
+ for (const model of enriched) {
36
+ if (renameMap[model.id]) {
37
+ model.displayName = renameMap[model.id];
38
+ }
39
+ }
33
40
  enriched.sort((a, b) => a.displayName.localeCompare(b.displayName));
34
41
  return enriched;
35
42
  }
@@ -0,0 +1,12 @@
1
+ import { type BrainPaths } from "../config/paths.js";
2
+ /** Every function here only ever touches renameMapFile; narrowed to that one
3
+ * field (rather than the full BrainPaths) so a test's fake paths object is
4
+ * actually type-checked instead of passing only because tsconfig excludes
5
+ * *.test.ts from the build. */
6
+ type RenameMapPaths = Pick<BrainPaths, "renameMapFile">;
7
+ export declare function loadRenameMap(paths?: RenameMapPaths): Record<string, string>;
8
+ export declare function saveRenameMap(map: Record<string, string>, paths?: RenameMapPaths): void;
9
+ export declare function updateDisplayName(modelId: string, displayName: string, paths?: RenameMapPaths): Record<string, string>;
10
+ export declare function deleteDisplayName(modelId: string, paths?: RenameMapPaths): Record<string, string>;
11
+ export {};
12
+ //# sourceMappingURL=rename-map.d.ts.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * User-defined model display-name overrides, keyed by model id, persisted at
3
+ * `$OTTO_HOME/otto-brain/rename-map.json`. Kept as its own file (rather than a
4
+ * field on the profiles store) so renaming a model never touches the
5
+ * calibration/profile data profiles.json carries.
6
+ */
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { z } from "zod";
9
+ import { resolveBrainPaths } from "../config/paths.js";
10
+ import { writePrivateFileAtomicSync } from "../config/private-files.js";
11
+ const RenameMapSchema = z.record(z.string());
12
+ export function loadRenameMap(paths = resolveBrainPaths()) {
13
+ if (!existsSync(paths.renameMapFile))
14
+ return {};
15
+ try {
16
+ const parsed = JSON.parse(readFileSync(paths.renameMapFile, "utf8"));
17
+ const result = RenameMapSchema.safeParse(parsed);
18
+ return result.success ? result.data : {};
19
+ }
20
+ catch {
21
+ return {};
22
+ }
23
+ }
24
+ export function saveRenameMap(map, paths = resolveBrainPaths()) {
25
+ writePrivateFileAtomicSync(paths.renameMapFile, `${JSON.stringify(map, null, 2)}\n`);
26
+ }
27
+ export function updateDisplayName(modelId, displayName, paths = resolveBrainPaths()) {
28
+ const map = loadRenameMap(paths);
29
+ map[modelId] = displayName;
30
+ saveRenameMap(map, paths);
31
+ return map;
32
+ }
33
+ export function deleteDisplayName(modelId, paths = resolveBrainPaths()) {
34
+ const map = loadRenameMap(paths);
35
+ delete map[modelId];
36
+ saveRenameMap(map, paths);
37
+ return map;
38
+ }
39
+ //# sourceMappingURL=rename-map.js.map
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Translates a profile into llama-server arguments and builds the PATH the child
3
+ * needs. Runtime-source agnostic: works the same for an LM Studio runtime or a
4
+ * managed one, since both resolve to a `Runtime` (exe + optional vendorDir).
5
+ */
1
6
  import type { Profile } from "../config/schema.js";
2
7
  import type { Runtime } from "../types.js";
3
8
  export interface ServeTarget {
@@ -5,10 +10,18 @@ export interface ServeTarget {
5
10
  host?: string;
6
11
  }
7
12
  /**
8
- * PATH value the child process needs so the stub can resolve its DLLs. Both the
9
- * runtime dir and its vendor dir go first, ahead of the inherited PATH.
13
+ * Loader environment the child process needs so it can resolve its shared
14
+ * libraries. Both the runtime dir and its vendor dir go first, ahead of the
15
+ * inherited values.
16
+ *
17
+ * PATH is the Windows half of this (the DLL-stub trap). The other two platforms
18
+ * do not read PATH for libraries at all: a llama.cpp tarball puts
19
+ * `libggml*.so`/`libllama.so` (or the `.dylib` equivalents) next to the binary,
20
+ * so Linux needs LD_LIBRARY_PATH and macOS needs DYLD_LIBRARY_PATH or the
21
+ * binary dies at load with an unresolved-library error before it prints a line.
22
+ * PATH is still set everywhere - harmless, and it keeps the shape uniform.
10
23
  */
11
- export declare function buildEnv(runtime: Runtime, baseEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
24
+ export declare function buildEnv(runtime: Runtime, baseEnv?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): NodeJS.ProcessEnv;
12
25
  /**
13
26
  * Translate a profile into llama-server arguments.
14
27
  *
@@ -1,21 +1,27 @@
1
1
  /**
2
- * Translates a profile into llama-server arguments and builds the PATH the child
3
- * needs. Runtime-source agnostic: works the same for an LM Studio runtime or a
4
- * managed one, since both resolve to a `Runtime` (exe + optional vendorDir).
5
- */
6
- import path from "node:path";
7
- /**
8
- * PATH value the child process needs so the stub can resolve its DLLs. Both the
9
- * runtime dir and its vendor dir go first, ahead of the inherited PATH.
2
+ * Loader environment the child process needs so it can resolve its shared
3
+ * libraries. Both the runtime dir and its vendor dir go first, ahead of the
4
+ * inherited values.
5
+ *
6
+ * PATH is the Windows half of this (the DLL-stub trap). The other two platforms
7
+ * do not read PATH for libraries at all: a llama.cpp tarball puts
8
+ * `libggml*.so`/`libllama.so` (or the `.dylib` equivalents) next to the binary,
9
+ * so Linux needs LD_LIBRARY_PATH and macOS needs DYLD_LIBRARY_PATH or the
10
+ * binary dies at load with an unresolved-library error before it prints a line.
11
+ * PATH is still set everywhere - harmless, and it keeps the shape uniform.
10
12
  */
11
- export function buildEnv(runtime, baseEnv = process.env) {
13
+ export function buildEnv(runtime, baseEnv = process.env, platform = process.platform) {
12
14
  const parts = [runtime.dir];
13
15
  if (runtime.vendorDir)
14
16
  parts.push(runtime.vendorDir);
15
- return {
16
- ...baseEnv,
17
- PATH: `${parts.join(path.delimiter)}${path.delimiter}${baseEnv.PATH || ""}`,
18
- };
17
+ const delimiter = platform === "win32" ? ";" : ":";
18
+ const prepend = (existing) => `${parts.join(delimiter)}${delimiter}${existing || ""}`;
19
+ const env = { ...baseEnv, PATH: prepend(baseEnv.PATH) };
20
+ if (platform === "darwin")
21
+ env.DYLD_LIBRARY_PATH = prepend(baseEnv.DYLD_LIBRARY_PATH);
22
+ else if (platform !== "win32")
23
+ env.LD_LIBRARY_PATH = prepend(baseEnv.LD_LIBRARY_PATH);
24
+ return env;
19
25
  }
20
26
  /**
21
27
  * Translate a profile into llama-server arguments.
@@ -1,13 +1,19 @@
1
1
  import type { BrainConfig } from "../config/schema.js";
2
2
  import type { Runtime } from "../types.js";
3
- import { type InstallProgress } from "./managed.js";
3
+ import { type InstallProgress, type RuntimeTarget } from "./managed.js";
4
4
  export { BACKENDS_DIR, LMSTUDIO_ROOT, listRuntimes as listLmStudioRuntimes } from "./lmstudio.js";
5
5
  export { buildArgs, buildEnv, formatCommand, type ServeTarget } from "./args.js";
6
- export { installManagedRuntime, listManagedRuntimes, defaultRuntimeSpec, DEFAULT_LLAMA_BUILD, type RuntimeSpec, type InstallProgress, } from "./managed.js";
6
+ export { installManagedRuntime, listManagedRuntimes, listRuntimeDevices, verifyRuntimeExecutable, defaultRuntimeSpec, extractArchive, resolveRuntimeVariant, serverExeName, supportedVariants, DEFAULT_LLAMA_BUILD, type RuntimeSpec, type RuntimeTarget, type RuntimeVariant, type InstallProgress, } from "./managed.js";
7
7
  /** Every runtime available on this machine, managed first then LM Studio. */
8
8
  export declare function listAllRuntimes(env?: NodeJS.ProcessEnv): Runtime[];
9
+ /**
10
+ * Whether this machine has an NVIDIA GPU, for picking a managed build. Returns
11
+ * false rather than throwing when nvidia-smi is absent, which is the normal
12
+ * case on macOS and on AMD/Intel machines.
13
+ */
14
+ export declare function probeNvidiaGpu(): Promise<boolean>;
9
15
  /** The runtime to use given config, or null when none is available. */
10
16
  export declare function resolveRuntime(config: BrainConfig, env?: NodeJS.ProcessEnv): Runtime | null;
11
17
  /** Ensure a runtime exists, downloading the default managed build if none does. */
12
- export declare function ensureRuntime(config: BrainConfig, env?: NodeJS.ProcessEnv, onProgress?: (progress: InstallProgress) => void): Promise<Runtime>;
18
+ export declare function ensureRuntime(config: BrainConfig, env?: NodeJS.ProcessEnv, onProgress?: (progress: InstallProgress) => void, target?: RuntimeTarget): Promise<Runtime>;
13
19
  //# sourceMappingURL=index.d.ts.map
@@ -4,18 +4,32 @@
4
4
  * path) and `lmstudio` (discovered from an existing LM Studio install, a
5
5
  * zero-download fast path). Selection follows config: an explicit path override
6
6
  * wins; otherwise `auto` prefers a managed runtime and falls back to LM Studio.
7
+ *
8
+ * Both providers are cross-platform. Which accelerator a managed install picks
9
+ * is decided in `managed.resolveRuntimeVariant` from the platform, the arch and
10
+ * whether an NVIDIA GPU answered - `probeNvidiaGpu` below is the one place that
11
+ * asks, so the download layer stays free of process spawning.
7
12
  */
13
+ import { query as queryGpu } from "../gpu.js";
8
14
  import { resolveBrainPaths } from "../config/paths.js";
9
15
  import { listRuntimes as listLmStudioRuntimes, resolveOverride } from "./lmstudio.js";
10
16
  import { defaultRuntimeSpec, installManagedRuntime, listManagedRuntimes, } from "./managed.js";
11
17
  export { BACKENDS_DIR, LMSTUDIO_ROOT, listRuntimes as listLmStudioRuntimes } from "./lmstudio.js";
12
18
  export { buildArgs, buildEnv, formatCommand } from "./args.js";
13
- export { installManagedRuntime, listManagedRuntimes, defaultRuntimeSpec, DEFAULT_LLAMA_BUILD, } from "./managed.js";
19
+ export { installManagedRuntime, listManagedRuntimes, listRuntimeDevices, verifyRuntimeExecutable, defaultRuntimeSpec, extractArchive, resolveRuntimeVariant, serverExeName, supportedVariants, DEFAULT_LLAMA_BUILD, } from "./managed.js";
14
20
  /** Every runtime available on this machine, managed first then LM Studio. */
15
21
  export function listAllRuntimes(env = process.env) {
16
22
  const paths = resolveBrainPaths(env);
17
23
  return [...listManagedRuntimes(paths.runtimesDir), ...listLmStudioRuntimes()];
18
24
  }
25
+ /**
26
+ * Whether this machine has an NVIDIA GPU, for picking a managed build. Returns
27
+ * false rather than throwing when nvidia-smi is absent, which is the normal
28
+ * case on macOS and on AMD/Intel machines.
29
+ */
30
+ export async function probeNvidiaGpu() {
31
+ return (await queryGpu()) !== null;
32
+ }
19
33
  /** The runtime to use given config, or null when none is available. */
20
34
  export function resolveRuntime(config, env = process.env) {
21
35
  const rc = config.runtime;
@@ -31,11 +45,15 @@ export function resolveRuntime(config, env = process.env) {
31
45
  return managed[0] ?? lmstudio[0] ?? null; // auto
32
46
  }
33
47
  /** Ensure a runtime exists, downloading the default managed build if none does. */
34
- export async function ensureRuntime(config, env = process.env, onProgress) {
48
+ export async function ensureRuntime(config, env = process.env, onProgress, target = {}) {
35
49
  const existing = resolveRuntime(config, env);
36
50
  if (existing)
37
51
  return existing;
38
52
  const paths = resolveBrainPaths(env);
39
- return installManagedRuntime(defaultRuntimeSpec(), paths.runtimesDir, onProgress);
53
+ const resolved = {
54
+ ...target,
55
+ hasNvidiaGpu: target.hasNvidiaGpu ?? (await probeNvidiaGpu()),
56
+ };
57
+ return installManagedRuntime(defaultRuntimeSpec(null, resolved), paths.runtimesDir, onProgress);
40
58
  }
41
59
  //# sourceMappingURL=index.js.map
@@ -4,7 +4,7 @@ export declare const BACKENDS_DIR: string;
4
4
  export declare function extractVersion(dirName: string): string;
5
5
  /** Compare dotted version strings numerically, descending. */
6
6
  export declare function compareVersionsDesc(a: string, b: string): number;
7
- export declare function listRuntimes(backendsDir?: string): Runtime[];
7
+ export declare function listRuntimes(backendsDir?: string, platform?: NodeJS.Platform): Runtime[];
8
8
  /** Resolve an explicit runtime directory or exe override into a Runtime. */
9
- export declare function resolveOverride(override: string): Runtime;
9
+ export declare function resolveOverride(override: string, platform?: NodeJS.Platform): Runtime;
10
10
  //# sourceMappingURL=lmstudio.d.ts.map
@@ -1,33 +1,73 @@
1
1
  /**
2
- * Locates the llama-server binary shipped inside LM Studio.
2
+ * Locates the llama-server binary shipped inside LM Studio, on all three
3
+ * desktop platforms. LM Studio keeps its backends under `~/.lmstudio` on
4
+ * Windows, macOS and Linux alike, so only the directory naming and the binary
5
+ * name differ per platform.
3
6
  *
4
- * Important gotcha: that executable is a ~20KB stub. Launching it without the
5
- * matching `backends/vendor/...` directory on PATH fails with
7
+ * Important gotcha (Windows): that executable is a ~20KB stub. Launching it
8
+ * without the matching `backends/vendor/...` directory on PATH fails with
6
9
  * STATUS_DLL_NOT_FOUND (0xC0000135) and prints absolutely nothing, so we always
7
- * pair a runtime with its vendor directory. This is one of two runtime sources
8
- * (the other being the self-contained `managed` runtime); it stays as a
9
- * zero-download fast path when LM Studio is already installed.
10
+ * pair a runtime with its vendor directory, and a Windows runtime whose vendor
11
+ * dir is missing is skipped rather than offered. macOS and Linux builds are
12
+ * self-contained and fail loudly through the dynamic loader when they are not,
13
+ * which is why the name-shape fallback below is enabled only there.
14
+ *
15
+ * This is one of two runtime sources (the other being the self-contained
16
+ * `managed` runtime); it stays as a zero-download fast path when LM Studio is
17
+ * already installed.
10
18
  */
11
19
  import fs from "node:fs";
12
20
  import os from "node:os";
13
21
  import path from "node:path";
22
+ import { serverExeName } from "./managed.js";
14
23
  export const LMSTUDIO_ROOT = path.join(os.homedir(), ".lmstudio");
15
24
  export const BACKENDS_DIR = path.join(LMSTUDIO_ROOT, "extensions", "backends");
16
- // Most preferred first. Each entry maps a runtime prefix to its vendor dir.
17
- const RUNTIME_PREFERENCE = [
18
- {
19
- prefix: "llama.cpp-win-x86_64-nvidia-cuda12-",
20
- vendor: "win-llama-cuda12-vendor-v2",
21
- label: "CUDA 12",
22
- },
23
- {
24
- prefix: "llama.cpp-win-x86_64-nvidia-cuda-",
25
- vendor: "win-llama-cuda-vendor-v2",
26
- label: "CUDA 11",
27
- },
28
- { prefix: "llama.cpp-win-x86_64-vulkan-", vendor: "win-llama-vulkan-vendor-v2", label: "Vulkan" },
29
- { prefix: "llama.cpp-win-x86_64-avx2-", vendor: null, label: "CPU (AVX2)" },
30
- ];
25
+ /**
26
+ * Most preferred first, per platform. Each entry maps a runtime directory
27
+ * prefix to its vendor dir.
28
+ *
29
+ * Prefix (not substring) matching is deliberate: a CUDA directory is named
30
+ * `llama.cpp-win-x86_64-nvidia-cuda12-avx2-<version>`, so a substring rule for
31
+ * the AVX2 entry would match it a second time and offer the same runtime twice
32
+ * under the wrong label.
33
+ *
34
+ * The Windows rows are verified against a real install. The macOS and Linux
35
+ * rows follow LM Studio's documented naming but have not been read off a live
36
+ * install here - the shape fallback in `listRuntimes` is what makes discovery
37
+ * correct on those platforms regardless.
38
+ */
39
+ const PREFERENCES = {
40
+ win32: [
41
+ {
42
+ prefix: "llama.cpp-win-x86_64-nvidia-cuda12-",
43
+ vendor: "win-llama-cuda12-vendor-v2",
44
+ label: "CUDA 12",
45
+ },
46
+ {
47
+ prefix: "llama.cpp-win-x86_64-nvidia-cuda-",
48
+ vendor: "win-llama-cuda-vendor-v2",
49
+ label: "CUDA 11",
50
+ },
51
+ {
52
+ prefix: "llama.cpp-win-x86_64-vulkan-",
53
+ vendor: "win-llama-vulkan-vendor-v2",
54
+ label: "Vulkan",
55
+ },
56
+ { prefix: "llama.cpp-win-x86_64-avx2-", vendor: null, label: "CPU (AVX2)" },
57
+ ],
58
+ darwin: [
59
+ { prefix: "llama.cpp-mac-arm64-apple-metal-", vendor: null, label: "Metal" },
60
+ { prefix: "llama.cpp-mac-arm64-", vendor: null, label: "CPU (arm64)" },
61
+ { prefix: "llama.cpp-mac-x86_64-", vendor: null, label: "CPU (x86_64)" },
62
+ ],
63
+ linux: [
64
+ { prefix: "llama.cpp-linux-x86_64-nvidia-cuda12-", vendor: null, label: "CUDA 12" },
65
+ { prefix: "llama.cpp-linux-x86_64-nvidia-cuda-", vendor: null, label: "CUDA 11" },
66
+ { prefix: "llama.cpp-linux-x86_64-vulkan-", vendor: null, label: "Vulkan" },
67
+ { prefix: "llama.cpp-linux-x86_64-avx2-", vendor: null, label: "CPU (AVX2)" },
68
+ { prefix: "llama.cpp-linux-aarch64-", vendor: null, label: "CPU (aarch64)" },
69
+ ],
70
+ };
31
71
  // Directory names carry an instruction-set segment before the version
32
72
  // (…-cuda12-avx2-2.24.0), so take the trailing dotted number, not the remainder.
33
73
  const VERSION_SUFFIX = /(\d+(?:\.\d+)+)$/;
@@ -46,40 +86,87 @@ export function compareVersionsDesc(a, b) {
46
86
  }
47
87
  return 0;
48
88
  }
49
- export function listRuntimes(backendsDir = BACKENDS_DIR) {
89
+ /** A readable label for a directory discovered outside the preference table. */
90
+ function labelFromDirName(dirName) {
91
+ const lower = dirName.toLowerCase();
92
+ if (lower.includes("cuda12"))
93
+ return "CUDA 12";
94
+ if (lower.includes("cuda"))
95
+ return "CUDA";
96
+ if (lower.includes("metal"))
97
+ return "Metal";
98
+ if (lower.includes("vulkan"))
99
+ return "Vulkan";
100
+ if (lower.includes("rocm") || lower.includes("hip"))
101
+ return "ROCm";
102
+ if (lower.includes("avx2"))
103
+ return "CPU (AVX2)";
104
+ return "LM Studio runtime";
105
+ }
106
+ export function listRuntimes(backendsDir = BACKENDS_DIR, platform = process.platform) {
50
107
  if (!fs.existsSync(backendsDir))
51
108
  return [];
109
+ const exeName = serverExeName(platform);
52
110
  const entries = fs
53
111
  .readdirSync(backendsDir, { withFileTypes: true })
54
112
  .filter((e) => e.isDirectory())
55
113
  .map((e) => e.name);
56
114
  const found = [];
57
- for (const pref of RUNTIME_PREFERENCE) {
115
+ const claimed = new Set();
116
+ for (const pref of PREFERENCES[platform] ?? []) {
58
117
  const matches = entries
59
- .filter((name) => name.startsWith(pref.prefix))
118
+ .filter((name) => name.startsWith(pref.prefix) && !claimed.has(name))
60
119
  .map((name) => ({ name, version: extractVersion(name) }))
61
- .filter(({ name }) => fs.existsSync(path.join(backendsDir, name, "llama-server.exe")))
120
+ .filter(({ name }) => fs.existsSync(path.join(backendsDir, name, exeName)))
62
121
  .sort((a, b) => compareVersionsDesc(a.version, b.version));
63
122
  for (const match of matches) {
64
123
  const vendorDir = pref.vendor ? path.join(backendsDir, "vendor", pref.vendor) : null;
65
124
  // A runtime whose vendor DLLs are missing cannot launch; skip it.
66
125
  if (vendorDir && !fs.existsSync(vendorDir))
67
126
  continue;
127
+ claimed.add(match.name);
68
128
  found.push({
69
129
  label: pref.label,
70
130
  version: match.version,
71
131
  dir: path.join(backendsDir, match.name),
72
- exe: path.join(backendsDir, match.name, "llama-server.exe"),
132
+ exe: path.join(backendsDir, match.name, exeName),
73
133
  vendorDir,
74
134
  source: "lmstudio",
75
135
  });
76
136
  }
77
137
  }
138
+ // Shape fallback: anything that holds a llama-server binary is usable on the
139
+ // self-contained platforms, whatever LM Studio decided to call the directory.
140
+ // Not applied on Windows, where an unpaired stub launches and dies silently.
141
+ if (platform !== "win32") {
142
+ const extra = entries
143
+ .filter((name) => !claimed.has(name) && name !== "vendor")
144
+ .filter((name) => fs.existsSync(path.join(backendsDir, name, exeName)))
145
+ .map((name) => ({ name, version: extractVersion(name) }))
146
+ .sort((a, b) => compareVersionsDesc(a.version, b.version));
147
+ for (const match of extra) {
148
+ found.push({
149
+ label: labelFromDirName(match.name),
150
+ version: match.version,
151
+ dir: path.join(backendsDir, match.name),
152
+ exe: path.join(backendsDir, match.name, exeName),
153
+ vendorDir: null,
154
+ source: "lmstudio",
155
+ });
156
+ }
157
+ }
78
158
  return found;
79
159
  }
80
160
  /** Resolve an explicit runtime directory or exe override into a Runtime. */
81
- export function resolveOverride(override) {
82
- const exe = override.endsWith(".exe") ? override : path.join(override, "llama-server.exe");
161
+ export function resolveOverride(override, platform = process.platform) {
162
+ const exeName = serverExeName(platform);
163
+ // An override may name the binary directly or the directory holding it. On
164
+ // non-Windows the binary has no extension, so "is it a file?" is the only
165
+ // reliable test - a bare `.../llama-server` path looks exactly like a dir.
166
+ const looksLikeExe = path.basename(override).toLowerCase() === exeName.toLowerCase() ||
167
+ (platform === "win32" && override.toLowerCase().endsWith(".exe")) ||
168
+ (fs.existsSync(override) && fs.statSync(override).isFile());
169
+ const exe = looksLikeExe ? override : path.join(override, exeName);
83
170
  if (!fs.existsSync(exe))
84
171
  throw new Error(`llama-server not found at ${exe}`);
85
172
  const dir = path.dirname(exe);
@@ -1,9 +1,23 @@
1
1
  import type { Runtime } from "../types.js";
2
+ /** The accelerator a managed runtime is built against. */
3
+ export type RuntimeVariant = "cuda" | "metal" | "vulkan" | "cpu";
2
4
  export interface RuntimeSpec {
3
5
  label: string;
4
6
  version: string;
5
7
  /** One or more archive URLs, extracted in order into the same target dir. */
6
8
  assets: string[];
9
+ /** Platform the assets are built for; drives exe name and extraction. */
10
+ platform: NodeJS.Platform;
11
+ variant: RuntimeVariant;
12
+ }
13
+ /** What to install for. Any field left out is read from the current process. */
14
+ export interface RuntimeTarget {
15
+ platform?: NodeJS.Platform;
16
+ arch?: string;
17
+ /** Explicit accelerator, or "auto" to pick from platform + GPU presence. */
18
+ variant?: RuntimeVariant | "auto";
19
+ /** Whether an NVIDIA GPU was detected; only consulted by "auto". */
20
+ hasNvidiaGpu?: boolean;
7
21
  }
8
22
  export interface InstallProgress {
9
23
  phase: "downloading" | "extracting" | "done";
@@ -12,15 +26,65 @@ export interface InstallProgress {
12
26
  totalBytes?: number;
13
27
  }
14
28
  /**
15
- * The default runtime build. The llama.cpp release tag and CUDA asset names must
16
- * be pinned per platform; verify the URLs against the current release before
17
- * shipping. Overridable via config (`runtime.path`) or an explicit spec.
29
+ * The default runtime build. Bumping this requires re-reading the tag's asset
30
+ * names (see the module header) - the naming scheme is not stable across tags.
31
+ */
32
+ export declare const DEFAULT_LLAMA_BUILD = "b10265";
33
+ /** The binary name llama.cpp ships for a platform. */
34
+ export declare function serverExeName(platform?: NodeJS.Platform): string;
35
+ /**
36
+ * Pick the accelerator for a target. Deliberately conservative: it never
37
+ * chooses an accelerator whose asset does not exist for that platform/arch.
38
+ */
39
+ export declare function resolveRuntimeVariant(target?: RuntimeTarget): RuntimeVariant;
40
+ /**
41
+ * Build the runtime spec for a target. Throws when upstream publishes nothing
42
+ * for the combination, naming what it tried so the message is actionable.
43
+ */
44
+ export declare function defaultRuntimeSpec(build?: string | null | undefined, target?: RuntimeTarget): RuntimeSpec;
45
+ /** Variants with a published asset for a platform/arch, best first. */
46
+ export declare function supportedVariants(platform?: NodeJS.Platform, arch?: string): RuntimeVariant[];
47
+ /**
48
+ * A managed runtime is any dir under runtimesDir that contains llama-server,
49
+ * best accelerator first and newest build first within an accelerator.
50
+ */
51
+ export declare function listManagedRuntimes(runtimesDir: string, platform?: NodeJS.Platform): Runtime[];
52
+ /**
53
+ * The actionable message for a dynamic-loader failure, or null when the output
54
+ * is not one. Pure, so the classification is testable without spawning.
55
+ *
56
+ * Returning null for an unrecognised failure is deliberate: a future llama.cpp
57
+ * that exits non-zero from `--version` must not turn a perfectly usable install
58
+ * into a hard failure. Only a positively identified missing library throws.
59
+ */
60
+ export declare function missingLibraryFrom(stderr: string): string | null;
61
+ export declare function describeLoaderFailure(stderr: string, runtimeDir: string, platform?: NodeJS.Platform): string | null;
62
+ /**
63
+ * Run the freshly installed binary once, so a missing *system* library surfaces
64
+ * at install time naming the library, instead of hours later as an opaque
65
+ * supervisor crash.
66
+ *
67
+ * This is not hypothetical: no upstream Linux asset ships `libgomp.so.1`, which
68
+ * `llama-server` hard-links, so on a host without `libgomp1` the download and
69
+ * extract both succeed and the binary then dies with exit 127. `buildEnv` cannot
70
+ * fix that - the library is not in the runtime dir LD_LIBRARY_PATH points at.
71
+ */
72
+ export declare function verifyRuntimeExecutable(runtime: Runtime, platform?: NodeJS.Platform, arch?: string): Promise<void>;
73
+ /**
74
+ * Device lines out of `--list-devices` stdout, which is a header followed by one
75
+ * indented line per device, or the literal `(none)`. Pure half of
76
+ * `listRuntimeDevices`.
77
+ */
78
+ export declare function parseDeviceList(stdout: string): string[];
79
+ /**
80
+ * Devices the runtime's backends actually found, one line each. Empty means the
81
+ * accelerator resolved to nothing and inference would silently fall back to CPU,
82
+ * which is a real configuration: on WSL2 there is no NVIDIA Vulkan ICD, so a
83
+ * Vulkan runtime on an NVIDIA machine reports no device and runs ~41x slower at
84
+ * prefill without saying so. Never throws; a probe failure reads as "unknown".
18
85
  */
19
- export declare const DEFAULT_LLAMA_BUILD = "b4600";
20
- /** Build the default Windows CUDA 12 spec for a given llama.cpp build tag. */
21
- export declare function defaultRuntimeSpec(build?: string): RuntimeSpec;
22
- /** A managed runtime is any dir under runtimesDir that contains llama-server.exe. */
23
- export declare function listManagedRuntimes(runtimesDir: string): Runtime[];
86
+ export declare function listRuntimeDevices(runtime: Runtime, platform?: NodeJS.Platform): Promise<string[]>;
87
+ export declare function extractArchive(archivePath: string, destDir: string, platform?: NodeJS.Platform): Promise<void>;
24
88
  /** Download + extract a runtime spec into runtimesDir and return the Runtime. */
25
89
  export declare function installManagedRuntime(spec: RuntimeSpec, runtimesDir: string, onProgress?: (progress: InstallProgress) => void): Promise<Runtime>;
26
90
  //# sourceMappingURL=managed.d.ts.map