diff --git a/apps/runtime/src/agents/subscription.ts b/apps/runtime/src/agents/subscription.ts index 74155e68..a8de03eb 100644 --- a/apps/runtime/src/agents/subscription.ts +++ b/apps/runtime/src/agents/subscription.ts @@ -1,7 +1,6 @@ import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; -import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { homedir } from "node:os"; +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { createInterface } from "node:readline"; import { @@ -10,6 +9,7 @@ import { CLIENTS, type ClientId, cursorWorkspace, + ownCursorServers, resolveEnv, } from "@engenty/local-models/clients"; import type { Lang } from "@engenty/wizards-shared/definition"; @@ -45,8 +45,8 @@ import type { TurnClock } from "./turn-clock.js"; */ export type SubscriptionClient = ClientId; -/** The clients whose subscription can answer the studio chat. */ -const SUBSCRIPTION_CLIENTS = CLIENT_IDS; +/** The clients whose subscription can answer the studio chat: those that take its MCP tools. */ +const SUBSCRIPTION_CLIENTS = CLIENT_IDS.filter((id) => CLIENTS[id].tools); /** The environment variable Codex reads this server's bearer key from. */ const CODEX_KEY_VAR = "WIZARDS_MCP_KEY"; @@ -89,18 +89,6 @@ function mcpConfig(): string { return file; } -/** The server names in the person's own Cursor config, which the chat's workspace denies. */ -function ownCursorServers(): string[] { - const file = join(homedir(), ".cursor", "mcp.json"); - try { - return existsSync(file) - ? Object.keys(JSON.parse(readFileSync(file, "utf8")).mcpServers ?? {}) - : []; - } catch { - return []; - } -} - const SYSTEM = (wizardId: string) => `${prompt("architect", "persona")}\n\n${prompt("architect", "subscription.system", { wizard_id: wizardId })}\n\n${contentPolicy()}`; diff --git a/apps/runtime/src/cli/environment.ts b/apps/runtime/src/cli/environment.ts index b8d901f3..bcd139e7 100644 --- a/apps/runtime/src/cli/environment.ts +++ b/apps/runtime/src/cli/environment.ts @@ -35,6 +35,8 @@ const INHERITED = new Set([ "CHROME_PATH", "FFMPEG_PATH", "OLLAMA_URL", + "LMSTUDIO_URL", + "LM_API_TOKEN", "SANDBOX", "SANDBOX_ENABLED", "SANDBOX_IMAGE", diff --git a/apps/runtime/src/cli/ollama.ts b/apps/runtime/src/cli/ollama.ts index 9ab2fb5e..a68eabb6 100644 --- a/apps/runtime/src/cli/ollama.ts +++ b/apps/runtime/src/cli/ollama.ts @@ -1,23 +1,6 @@ -import { spawn } from "node:child_process"; -import { - accessSync, - constants, - existsSync, - mkdirSync, - mkdtempSync, - openSync, - realpathSync, - rmSync, -} from "node:fs"; -import { statfs } from "node:fs/promises"; -import { homedir, tmpdir } from "node:os"; -import { join } from "node:path"; -import { setTimeout as sleep } from "node:timers/promises"; import { ollamaAddress, ollamaState } from "@engenty/local-models/ollama"; +import { findOllama } from "@engenty/model-setup/server"; import { decisionModelIn } from "../decision-model.js"; -import { runLogged } from "./exec.js"; -import type { Layout } from "./home.js"; -import { findOnPath } from "./machine.js"; /** The first Ollama that answers decision questions at /v1/systemone. */ const DECISIONS_SINCE = [0, 35, 0]; @@ -25,25 +8,6 @@ const DECISIONS_SINCE = [0, 35, 0]; /** What Clef-flash takes on disk, and about as much memory while it answers, in GB. */ export const DECISION_MODEL_GB = 11; -/** The Ollama app on a Mac: its server and its command are inside it. */ -const MAC_APPS = ["/Applications/Ollama.app", join(homedir(), "Applications", "Ollama.app")]; -const MAC_DOWNLOAD = "https://ollama.com/download/Ollama-darwin.zip"; -/** Ollama's own installer on Linux: it puts the server in a systemd service, with sudo. */ -const LINUX_SCRIPT = "https://ollama.com/install.sh"; -/** - * What that installer needs and a fresh Debian lacks: zstd, to unpack Ollama. Installed first - * with the system's package manager, under the same password. - */ -const LINUX_ZSTD = [ - "if ! command -v zstd >/dev/null 2>&1; then", - " if command -v apt-get >/dev/null 2>&1; then sudo apt-get update -qq && sudo apt-get install -y -qq zstd", - " elif command -v dnf >/dev/null 2>&1; then sudo dnf install -y -q zstd", - " elif command -v pacman >/dev/null 2>&1; then sudo pacman -S --noconfirm --needed zstd", - " elif command -v zypper >/dev/null 2>&1; then sudo zypper --non-interactive install zstd", - " fi", - "fi", -].join("\n"); - export interface LocalOllamaState { /** The `ollama` command; null where Ollama is not installed. */ path: string | null; @@ -53,26 +17,6 @@ export interface LocalOllamaState { model: string | null; } -function executable(file: string): boolean { - try { - accessSync(file, constants.X_OK); - return true; - } catch { - return false; - } -} - -/** The `ollama` command: on the PATH, or inside the app on a Mac that never linked it. */ -export function findOllama(env: NodeJS.ProcessEnv = process.env): string | null { - const onPath = findOnPath("ollama", env.PATH ?? ""); - if (onPath || process.platform !== "darwin") { - return onPath; - } - return ( - MAC_APPS.map((app) => join(app, "Contents", "Resources", "ollama")).find(executable) ?? null - ); -} - /** Ollama on this computer: its command, the server that answers at OLLAMA_URL, and its decision model. */ export async function localOllama(env: NodeJS.ProcessEnv = process.env): Promise { const { version, models } = await ollamaState(ollamaAddress(env)); @@ -91,147 +35,6 @@ export function servesDecisions(version: string): boolean { return true; } -/** Free space where Ollama keeps its models (the home folder), in GB. */ -export async function freeGb(dir = homedir()): Promise { - try { - const stats = await statfs(dir); - return Math.floor((stats.bavail * stats.bsize) / 2 ** 30); - } catch { - return null; - } -} - -/** The app an `ollama` command belongs to on a Mac; null for one from Homebrew or elsewhere. */ -function macApp(path: string | null): string | null { - if (process.platform !== "darwin") { - return null; - } - if (!path) { - return MAC_APPS.find((app) => existsSync(app)) ?? null; - } - try { - const real = realpathSync(path); - const at = real.indexOf(".app/"); - return at > 0 ? real.slice(0, at + 4) : null; - } catch { - return null; - } -} - -export interface Outcome { - ok: boolean; - message: string; -} - -/** - * Installs Ollama. On a Mac its app goes into Applications (~/Applications where that is not - * writable) and asks for no password; on Linux Ollama's own script runs in this terminal and - * asks for one, as it installs a system service. - */ -export async function installOllama( - paths: Layout, - onLine: (line: string) => void, -): Promise { - const logFile = join(paths.logs, "install.log"); - if (process.platform === "darwin") { - let target = "/Applications"; - try { - accessSync(target, constants.W_OK); - } catch { - target = join(homedir(), "Applications"); - mkdirSync(target, { recursive: true }); - } - const tmp = mkdtempSync(join(tmpdir(), "ollama-")); - try { - const zip = join(tmp, "Ollama.zip"); - const download = await runLogged("curl", ["-fsSL", MAC_DOWNLOAD, "-o", zip], { - logFile, - onLine, - }); - if (download.code !== 0) { - return { ok: false, message: `The download failed. ${lastLine(download.tail)}` }; - } - const unpack = await runLogged("ditto", ["-x", "-k", zip, target], { logFile, onLine }); - if (unpack.code !== 0) { - return { ok: false, message: `It could not be unpacked. ${lastLine(unpack.tail)}` }; - } - return { ok: true, message: join(target, "Ollama.app") }; - } finally { - rmSync(tmp, { recursive: true, force: true }); - } - } - if (process.platform === "linux") { - const code = await new Promise((resolve) => { - const child = spawn("sh", ["-c", `${LINUX_ZSTD}\ncurl -fsSL ${LINUX_SCRIPT} | sh`], { - stdio: "inherit", - }); - child.on("error", () => resolve(127)); - child.on("close", (status) => resolve(status ?? 1)); - }); - return code === 0 - ? { ok: true, message: findOllama() ?? "ollama" } - : { ok: false, message: `Ollama’s installer stopped (exit ${code}).` }; - } - return { ok: false, message: "Ollama is installed by this setup on macOS and Linux only." }; -} - -const lastLine = (text: string) => text.split("\n").pop() ?? ""; - -/** - * Whether the Ollama app asks for the Mac's password when it starts: the first time, it wants to - * link its `ollama` command into /usr/local/bin, and its server waits for the answer (cancel - * works too). Not once that link points into the app. - */ -export function appAsksForPassword(path: string | null): boolean { - const app = macApp(path); - if (!app) { - return false; - } - try { - return realpathSync("/usr/local/bin/ollama") !== join(app, "Contents", "Resources", "ollama"); - } catch { - return true; - } -} - -/** - * Starts Ollama's server where it does not run: the app on a Mac (it then starts at login by - * itself), Homebrew's service, else `ollama serve` in the background. Its version once it - * answers; null where it does not in time — three minutes for the app, which may wait for a - * password, half a minute otherwise. - */ -export async function startOllama(path: string | null, paths: Layout): Promise { - const logFile = join(paths.logs, "install.log"); - const app = macApp(path); - const brew = findOnPath("brew", process.env.PATH ?? ""); - let real = path ?? ""; - try { - real = path ? realpathSync(path) : ""; - } catch { - // a dangling link: started as it is - } - if (app) { - await runLogged("open", ["-g", app], { logFile }); - } else if (brew && real.includes("/Cellar/ollama/")) { - await runLogged(brew, ["services", "start", "ollama"], { logFile }); - } else if (path) { - mkdirSync(paths.logs, { recursive: true }); - const out = openSync(join(paths.logs, "ollama.log"), "a"); - spawn(path, ["serve"], { detached: true, stdio: ["ignore", out, out] }).unref(); - } else { - return null; - } - const deadline = Date.now() + (app ? 180_000 : 30_000); - while (Date.now() < deadline) { - const { version } = await localOllama(); - if (version) { - return version; - } - await sleep(500); - } - return null; -} - /** * Whether Ollama runs the model: one question it has to answer. Null when it does; otherwise * Ollama's reason, such as a newer Ollama that no longer runs a model in the format it was pulled diff --git a/apps/runtime/src/cli/setup.ts b/apps/runtime/src/cli/setup.ts index 808e65ad..df1d5d92 100644 --- a/apps/runtime/src/cli/setup.ts +++ b/apps/runtime/src/cli/setup.ts @@ -4,7 +4,14 @@ import { delimiter, join } from "node:path"; import * as p from "@clack/prompts"; import { ollamaAddress, pullModel } from "@engenty/local-models/ollama"; import { CLIENTS, type ClientEntry, installCommand } from "@engenty/model-setup"; -import { suggestedClient, vendorApp } from "@engenty/model-setup/server"; +import { + appAsksForPassword, + freeGb, + installOllama, + startOllama, + suggestedClient, + vendorApp, +} from "@engenty/model-setup/server"; import { LOCAL_DECISION_MODEL } from "../decision-model.js"; import { installAll, ON_DEMAND } from "../on-demand.js"; import { accountStep } from "./account.js"; @@ -23,16 +30,7 @@ import { writeInstallNote, } from "./home.js"; import { type ClientState, detectClients, findChrome, findFfmpeg, findOnPath } from "./machine.js"; -import { - appAsksForPassword, - DECISION_MODEL_GB, - decisionModelProblem, - freeGb, - installOllama, - localOllama, - servesDecisions, - startOllama, -} from "./ollama.js"; +import { DECISION_MODEL_GB, decisionModelProblem, localOllama, servesDecisions } from "./ollama.js"; import { runningRuntime, settings } from "./start.js"; import { badge, busy, cmd, cyan, dim, tilde } from "./ui.js"; @@ -319,7 +317,7 @@ async function decisionModelStep( if (!task) { p.log.info("Ollama’s own installer runs now and asks for your password."); } - const outcome = await installOllama(paths, (line) => task?.message(line)); + const outcome = await installOllama(paths.logs, (line) => task?.message(line)); if (!outcome.ok) { const text = `Ollama didn’t install. ${outcome.message}`; task ? task.error(text) : p.log.error(text); @@ -338,7 +336,7 @@ async function decisionModelStep( } const spinner = p.spinner(); spinner.start("Waiting for Ollama"); - version = await startOllama(ollama, paths); + version = await startOllama(ollama, paths.logs); if (!version) { spinner.error(`Ollama isn’t answering. Start it, then run ${cmd("setup")} again.`); return; diff --git a/apps/runtime/src/env.ts b/apps/runtime/src/env.ts index 751f40a5..25ae56ff 100644 --- a/apps/runtime/src/env.ts +++ b/apps/runtime/src/env.ts @@ -238,6 +238,7 @@ export const env = { */ browserFastLoop: str("BROWSER_FAST_LOOP") !== "off", ollamaUrl: str("OLLAMA_URL", "http://127.0.0.1:11434/v1"), + lmstudioUrl: str("LMSTUDIO_URL", "http://127.0.0.1:1234/v1"), /** What each model class runs on when this runtime resolves classes itself (own keys, Ollama). */ models: { diff --git a/apps/runtime/src/harness/clients.ts b/apps/runtime/src/harness/clients.ts index 355e18cc..07a13a12 100644 --- a/apps/runtime/src/harness/clients.ts +++ b/apps/runtime/src/harness/clients.ts @@ -20,7 +20,7 @@ import { modelOptions } from "./model.js"; import type { Harness } from "./types.js"; /** - * Claude Code, Codex and Cursor Agent as the runtime runs them: the clients of + * Claude Code, Codex, Antigravity and Cursor Agent as the runtime runs them: the clients of * @engenty/local-models/clients with the model each text class runs on, what the person reads * when the account cannot pay, and Codex's images. */ @@ -129,6 +129,16 @@ export const codex: Harness = harnessOf(CLIENTS.codex, { }, }); +/** The models carry their effort in the name (`withEffort`). */ +export const antigravity = harnessOf(CLIENTS.antigravity, { + classes: { + classifier: "gemini-3.8-flash-low", + low: "gemini-3.8-flash-medium", + standard: "gemini-3.8-flash-high", + high: "gemini-3.8-flash-high", + }, +}); + /** "auto" = the model the client picks itself; a binding `cursor/` names one. */ export const cursor = harnessOf(CLIENTS.cursor, { classes: { classifier: "auto", low: "auto", standard: "auto", high: "auto" }, diff --git a/apps/runtime/src/harness/index.ts b/apps/runtime/src/harness/index.ts index 947ff349..230721f0 100644 --- a/apps/runtime/src/harness/index.ts +++ b/apps/runtime/src/harness/index.ts @@ -4,8 +4,7 @@ import type { ClientSetupStatus } from "@engenty/model-setup"; import { ClientSetup } from "@engenty/model-setup/server"; import { inherited, runtimePath } from "../cli/environment.js"; import { layout } from "../cli/home.js"; -import { antigravity } from "./antigravity.js"; -import { claude, codex, cursor } from "./clients.js"; +import { antigravity, claude, codex, cursor } from "./clients.js"; import type { Harness, HarnessId } from "./types.js"; export { HARNESS_IDS, type Harness, type HarnessId } from "./types.js"; diff --git a/apps/runtime/src/local-models.ts b/apps/runtime/src/local-models.ts index a1807ac3..aaff8fb5 100644 --- a/apps/runtime/src/local-models.ts +++ b/apps/runtime/src/local-models.ts @@ -1,95 +1,19 @@ -import { totalmem } from "node:os"; -import { - fits, - installedModels as ollamaModels, - ollamaRoot, - ollamaState, - pullModel, -} from "@engenty/local-models/ollama"; +import { SERVERS } from "@engenty/local-models/servers"; +import { MODEL_JOBS, OFFERED_MODELS, type OfferedModel } from "@engenty/model-setup"; +import { LocalModels } from "@engenty/model-setup/server"; +import { layout } from "./cli/home.js"; import { env } from "./env.js"; -import { forgetLocalModels, localOllamaUrl } from "./models.js"; +import { embeddingModel, forgetLocalModels, localServerUrl } from "./models.js"; /** - * The models in Ollama on this computer, for Settings › Models: what is there and what each can - * do (Ollama's own `capabilities`), the models the Manage-App offers per job (`GET - * /v1/local-models` of the account's Manage-App), and the downloads and removals the studio - * starts. Text, search and decisions each pick their model from it. + * The servers for open models on this computer (@engenty/model-setup). Ollama's models come with + * the ones the Manage-App offers per job (`GET /v1/local-models` of the account's Manage-App): + * text, search and decisions each pick their model from it. LM Studio's are for text. */ -/** What a model does in the studio: a text class, the search of a space's knowledge, decisions. */ -export const LOCAL_JOBS = ["text", "search", "decision"] as const; -export type LocalJob = (typeof LOCAL_JOBS)[number]; - -/** A model the Manage-App offers for a job; the best of a job comes first. */ -export interface OfferedModel { - name: string; - job: LocalJob; - /** The download, in GB. */ - size: number; - /** About the memory it takes while it answers, in GB. */ - memory: number; - note: { en: string; de: string }; -} - -/** A model Ollama holds. */ -export interface InstalledModel { - name: string; - /** On disk, in GB. */ - size: number; - jobs: LocalJob[]; - /** As Ollama says: `completion`, `tools`, `vision`, `audio`, `embedding`, `decision`, … */ - capabilities: string[]; - /** `mlx` or `llamacpp`; null where Ollama does not say. */ - runner: string | null; - quantization: string | null; - /** In memory right now. */ - loaded: boolean; -} - -/** A download into Ollama: while it runs, and how it ended. */ -export interface LocalDownload { - model: string; - done: number; - total: number; - /** `ollama`: Ollama does not run on this computer; else what Ollama said. */ - error: string | null; - finished: boolean; -} - /** The share of the computer's memory a model may take and still leave room for the rest. */ const MEMORY_SHARE = 0.7; -/** The job a capability of Ollama's serves. */ -const JOB_OF: Record = { - completion: "text", - embedding: "search", - decision: "decision", -}; - -const gb = (bytes: number) => Math.round((bytes / 1e9) * 10) / 10; - -async function getJson(url: string, timeoutMs: number): Promise { - try { - const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }); - return res.ok ? ((await res.json()) as T) : null; - } catch { - return null; - } -} - -/** The models Ollama holds, with the jobs each can do here. */ -async function installedModels(root: string): Promise { - return (await ollamaModels(root)).map((m) => ({ - name: m.name, - size: gb(m.size), - jobs: LOCAL_JOBS.filter((job) => m.capabilities.some((c) => JOB_OF[c] === job)), - capabilities: m.capabilities, - runner: m.runner, - quantization: m.quantization, - loaded: m.running, - })); -} - /** The Manage-App's list at the last look: kept for an hour, asked again after five minutes when it did not answer. */ let offered: { models: OfferedModel[] | null; at: number } | null = null; @@ -97,136 +21,48 @@ async function offeredModels(): Promise { if (offered && Date.now() < offered.at) { return offered.models; } - const body = await getJson<{ models?: OfferedModel[] }>( - `${env.local.accountUrl}/v1/local-models`, - 3000, - ); - const models = body?.models?.filter((m) => LOCAL_JOBS.includes(m.job)) ?? null; - offered = { models, at: Date.now() + (models ? 60 : 5) * 60_000 }; - return models; -} - -const downloads = new Map(); - -/** While Ollama is being installed or started from the studio, and how that ended. */ -let ollamaStart: { running: boolean; error: string | null } | null = null; - -/** Ollama on this computer, its models and the ones to download, for the settings page. */ -export async function localModels() { - const url = await localOllamaUrl(); - const root = ollamaRoot(url); - const { findOllama, freeGb } = await import("./cli/ollama.js"); - const { version } = await ollamaState(root); - const memory = Math.round(totalmem() / 2 ** 30); - const installed = version ? await installedModels(root) : []; - const held = new Set(installed.map((m) => m.name)); - const list = await offeredModels(); - return { - ollama: { - url, - /** Null: Ollama does not answer at the address. */ - version, - /** The `ollama` command is on this computer, though it may not run. */ - installed: Boolean(version || findOllama()), - /** The studio can install Ollama itself: on a Mac, as the setup does. */ - canInstall: process.platform === "darwin", - start: ollamaStart, - }, - /** The computer's memory and the free space for models, in GB. */ - memory, - free: await freeGb(), - installed, - /** Null: the Manage-App did not answer, the list shows the installed models alone. */ - offered: - list?.map((m) => ({ - ...m, - installed: held.has(m.name) || held.has(`${m.name}:latest`), - fits: fits(m.memory, memory, MEMORY_SHARE), - })) ?? null, - downloads: [...downloads.values()], - }; -} - -/** - * Pulls a model into Ollama in the background; `then` runs once it ended well. A download of - * the same model that runs already is left to finish. - */ -export async function downloadLocalModel(model: string, then?: () => Promise) { - const running = downloads.get(model); - if (running && !running.finished) { - return; - } - const state: LocalDownload = { model, done: 0, total: 0, error: null, finished: false }; - downloads.set(model, state); - void pullModel(await localOllamaUrl(), model, (done, total) => { - state.done = done; - state.total = total; - }) - .then(async () => { - forgetLocalModels(); - state.finished = true; - // A finished download is done; the list shows the model itself now. - downloads.delete(model); - await then?.(); - }) - .catch((err: Error) => { - const unreachable = /fetch failed|ECONNREFUSED/i.test(`${err.message} ${err.cause ?? ""}`); - state.error = unreachable ? "ollama" : err.message; - state.finished = true; + let models: OfferedModel[] | null = null; + try { + const res = await fetch(`${env.local.accountUrl}/v1/local-models`, { + signal: AbortSignal.timeout(3000), }); -} - -/** Removes a model from Ollama, and a download of it that failed; Ollama's reason where it refuses. */ -export async function removeLocalModel(model: string): Promise { - downloads.delete(model); - forgetLocalModels(); - const res = await fetch(`${ollamaRoot(await localOllamaUrl())}/api/delete`, { - method: "DELETE", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ model }), - signal: AbortSignal.timeout(10_000), - }); - if (!res.ok) { - const text = (await res.text()).trim(); - let reason = text; - try { - reason = (JSON.parse(text) as { error?: string }).error ?? text; - } catch {} - throw new Error(reason || `Ollama answered ${res.status}.`); + const body = res.ok ? ((await res.json()) as { models?: OfferedModel[] }) : null; + models = body?.models?.filter((m) => MODEL_JOBS.includes(m.job)) ?? null; + } catch { + // Asked again in five minutes. } + offered = { models, at: Date.now() + (models ? 60 : 5) * 60_000 }; + return models; } -/** - * Installs Ollama where it is missing (on a Mac) and starts it, as `wizards setup` does, in the - * background; the settings page follows `ollama.start`. - */ -export async function startLocalOllama() { - if (ollamaStart?.running) { - return; - } - const state = { running: true, error: null as string | null }; - ollamaStart = state; - const { findOllama, installOllama, startOllama } = await import("./cli/ollama.js"); - const { layout } = await import("./cli/home.js"); - const paths = layout(); - void (async () => { - let path = findOllama(); - if (!path) { - const outcome = await installOllama(paths, () => undefined); - if (!outcome.ok) { - throw new Error(outcome.message); +/** The model the spaces are indexed with now. */ +const embeddedBy = async () => (await embeddingModel().catch(() => null))?.ref ?? null; + +const ollama = new LocalModels({ + server: SERVERS.ollama, + url: () => localServerUrl("ollama"), + offered: offeredModels, + share: MEMORY_SHARE, + logs: () => layout().logs, + changed: forgetLocalModels, + // Where the pulled model is the embedding model now, the spaces are indexed with it after. + async pulling() { + const before = await embeddedBy(); + return async () => { + if ((await embeddedBy()) !== before) { + const { reindexAll } = await import("./services/space-index.js"); + await reindexAll(); } - path = findOllama(); - } - if (!(await startOllama(path, paths))) { - throw new Error("Ollama isn’t answering."); - } - forgetLocalModels(); - })() - .catch((err: Error) => { - state.error = err.message; - }) - .finally(() => { - state.running = false; - }); -} + }; + }, +}); + +const lmStudio = new LocalModels({ + server: SERVERS.lmstudio, + url: () => localServerUrl("lmstudio"), + offered: () => OFFERED_MODELS.lmstudio, + share: MEMORY_SHARE, + logs: () => layout().logs, +}); + +export const localServers: readonly LocalModels[] = [ollama, lmStudio]; diff --git a/apps/runtime/src/models.ts b/apps/runtime/src/models.ts index 8f5d35e2..2613eca4 100644 --- a/apps/runtime/src/models.ts +++ b/apps/runtime/src/models.ts @@ -7,7 +7,9 @@ import { createGoogle } from "@ai-sdk/google"; import { createOpenAI } from "@ai-sdk/openai"; import { createReplicate } from "@ai-sdk/replicate"; import { ClientModel } from "@engenty/local-models/clients"; +import { lmStudioFetch, lmStudioRoot } from "@engenty/local-models/lmstudio"; import { ollamaRoot } from "@engenty/local-models/ollama"; +import { SERVERS, type ServerId } from "@engenty/local-models/servers"; import type { Lang, VideoResolution } from "@engenty/wizards-shared/definition"; import { DEFINITION_VERSION, @@ -95,7 +97,8 @@ export { isHarnessVendor } from "./harness/index.js"; * tenant of a Manage-App's runtime, or on the account a runtime that runs alone is linked to. * A runtime of a Manage-App keeps a tenant's own keys (sealed) and runs on its credits where it * has none. A binding is `[provider:]vendor/model`, e.g. `anthropic/claude-haiku-4.5` (AI - * Gateway), `openai:gpt-5.4-mini`, `fal:fal-ai/flux/schnell`, `ollama:qwen3`, `claude/sonnet` + * Gateway), `openai:gpt-5.4-mini`, `fal:fal-ai/flux/schnell`, `ollama:qwen3`, + * `lmstudio:google/gemma-4-12b`, `claude/sonnet` * (an installed client), or `credits`. */ export { ModelUnavailableError } from "./model-errors.js"; @@ -140,6 +143,7 @@ export interface LocalModelSettings { source: LocalSource; bindings: Partial>; ollamaUrl?: string; + lmstudioUrl?: string; /** The credits of the linked account step in for a class without a way of its own. Default: on. */ creditFallback?: boolean; /** Which decision model answers decisions (`DecisionChoice`). Default: `auto`. */ @@ -190,6 +194,7 @@ export interface ModelSettingsInput { source?: LocalSource; bindings?: Partial>; ollamaUrl?: string; + lmstudioUrl?: string; creditFallback?: boolean; decision?: DecisionChoice; decisionLocal?: string; @@ -370,6 +375,18 @@ function mergeBindings( return bindings; } +/** Where a server answers for this machine, as the settings name it. */ +function serverUrl(cfg: ModelConfig, id: ServerId): string { + return id === "ollama" + ? (cfg.settings.ollamaUrl ?? env.ollamaUrl) + : (cfg.settings.lmstudioUrl ?? env.lmstudioUrl); +} + +/** Where a server answers for this machine. */ +export async function localServerUrl(id: ServerId): Promise { + return serverUrl(await config(), id); +} + export function localModelSettings() { return { ...local.settings, @@ -377,7 +394,8 @@ export function localModelSettings() { bindings: Object.fromEntries( MODEL_CLASSES.map((c) => [c, ownRef(local, c) || local.settings.bindings[c] || ""]), ) as Record, - ollamaUrl: local.settings.ollamaUrl ?? env.ollamaUrl, + ollamaUrl: serverUrl(local, "ollama"), + lmstudioUrl: serverUrl(local, "lmstudio"), keys: Object.fromEntries(LOCAL_KEYS.map((k) => [k, Boolean(local.keys[k])])) as Record< LocalKey, boolean @@ -390,6 +408,7 @@ export async function saveLocalModels(input: ModelSettingsInput) { source: input.source ?? local.settings.source, bindings: mergeBindings(local.settings.bindings, input.bindings), ollamaUrl: input.ollamaUrl?.trim() || local.settings.ollamaUrl, + lmstudioUrl: input.lmstudioUrl?.trim() || local.settings.lmstudioUrl, creditFallback: input.creditFallback ?? local.settings.creditFallback, decision: input.decision ?? local.settings.decision, decisionLocal: input.decisionLocal?.trim() || local.settings.decisionLocal, @@ -460,8 +479,12 @@ function parse(ref: string): { provider: string | null; id: string; vendor: stri const vendorOf = (ref: string) => parse(ref).vendor; -/** A model on this machine: Ollama, or Apple Intelligence on a Mac (harness/apple.ts). */ -const isLocalProvider = (provider: string | null) => provider === "ollama" || provider === "apple"; +/** A server for open models on this machine (@engenty/local-models). */ +const isServer = (provider: string | null): provider is ServerId => + provider !== null && Object.hasOwn(SERVERS, provider); + +/** A model on this machine: a server's, or Apple Intelligence on a Mac (harness/apple.ts). */ +const isLocalProvider = (provider: string | null) => isServer(provider) || provider === "apple"; /** The part of `codex/default` after the client. */ const aliasOf = (id: string) => id.split("/").slice(1).join("/"); @@ -996,6 +1019,9 @@ async function installedClient(ref: string) { return client; } +/** Tokens a model of LM Studio is loaded to read: a step's documents, its tools and its answer. */ +const LMSTUDIO_CONTEXT = 32_768; + async function ownLanguageModel( cfg: ModelConfig, ref: string, @@ -1010,11 +1036,22 @@ async function ownLanguageModel( case "ollama": return { model: createOpenAI({ - baseURL: cfg.settings.ollamaUrl ?? env.ollamaUrl, + baseURL: serverUrl(cfg, "ollama"), apiKey: "ollama", }).chat(id), gateway: false, }; + case "lmstudio": { + const root = lmStudioRoot(serverUrl(cfg, "lmstudio")); + return { + model: createOpenAI({ + baseURL: `${root}/v1`, + apiKey: "lmstudio", + fetch: lmStudioFetch(root, { context: LMSTUDIO_CONTEXT }), + }).chat(id), + gateway: false, + }; + } case "apple": { const status = await appleStatus(); if (!status.available) { @@ -1409,11 +1446,6 @@ export function forgetLocalModels() { localDecision = null; } -/** Where Ollama answers for this machine (…/v1), as the settings name it. */ -export async function localOllamaUrl(): Promise { - return (await config()).settings.ollamaUrl ?? env.ollamaUrl; -} - /** * An embedding model, with `embedImage` where it embeds pictures too, into the same space as * text (EmbeddingGemma 2): a question then finds a photo or a PDF page by what it shows. @@ -1513,7 +1545,7 @@ async function embeddingBy( }; } case "local": { - const url = cfg.settings.ollamaUrl ?? env.ollamaUrl; + const url = serverUrl(cfg, "ollama"); const name = localEmbeddingName(cfg); const capabilities = await ollamaHolds(url, name); if (!capabilities) { @@ -1700,7 +1732,7 @@ async function decisionBy( } : null; case "local": { - const ollama = cfg.settings.ollamaUrl ?? env.ollamaUrl; + const ollama = serverUrl(cfg, "ollama"); const model = await localDecisionModel(ollama, cfg.settings.decisionLocal); return model ? { @@ -1791,7 +1823,7 @@ async function decisionSettings(cfg: ModelConfig) { /** The decision model asked for in Ollama on this computer. */ local: cfg.settings.decisionLocal ?? - (managed ? null : await ollamaDecisionModel(cfg.settings.ollamaUrl ?? env.ollamaUrl)) ?? + (managed ? null : await ollamaDecisionModel(serverUrl(cfg, "ollama"))) ?? LOCAL_DECISION_MODEL, }; } @@ -2113,7 +2145,8 @@ export async function modelSettings(lang: Lang = "en") { return { source: cfg.settings.source, bindings: stored.settings.bindings, - ollamaUrl: cfg.settings.ollamaUrl ?? env.ollamaUrl, + ollamaUrl: serverUrl(cfg, "ollama"), + lmstudioUrl: serverUrl(cfg, "lmstudio"), creditFallback: cfg.settings.creditFallback !== false, keys: Object.fromEntries(LOCAL_KEYS.map((k) => [k, Boolean(stored.keys[k])])) as Record< LocalKey, @@ -2254,24 +2287,28 @@ export async function setUpKey( return setupOutcome(); } -/** The setup's test of Ollama: it answers at the address and has a model to think with. */ -export async function setUpOllama(url: string, lang: Lang = "en"): Promise { +/** The setup's test of a server: it answers at the address and has a model to think with. */ +export async function setUpServer( + id: ServerId, + url: string, + lang: Lang = "en", +): Promise { + const server = SERVERS[id]; const base = url.trim().replace(/\/+$/, ""); - let models: string[]; - try { - const res = await fetch(`${base}/models`, { signal: AbortSignal.timeout(5_000) }); - const body = (await res.json()) as { data?: { id: string }[] }; - models = (body.data ?? []).map((m) => m.id); - } catch { - return { ok: false, message: serverText(lang, "ollamaUnreachable"), text: null }; + const { running } = await server.state(base); + if (!running) { + const message = serverText(lang, "serverUnreachable", { name: server.name }); + return { ok: false, message, text: null }; } + const models = (await server.models(base)).filter((m) => m.completion).map((m) => m.name); if (!models.length) { - return { ok: false, message: serverText(lang, "ollamaNoModel"), text: null }; + const message = serverText(lang, "serverNoModel", { name: server.name }); + return { ok: false, message, text: null }; } - const bound = local.settings.bindings.low?.replace(/^ollama:/, ""); + const bound = local.settings.bindings.low?.replace(`${id}:`, ""); const model = bound && models.includes(bound) ? bound : models[0]; - const text = Object.fromEntries(TEXT_CLASSES.map((c) => [c, `ollama:${model}`])); - await saveLocalModels({ ollamaUrl: base, bindings: freeClasses(text) }); + const text = Object.fromEntries(TEXT_CLASSES.map((c) => [c, `${id}:${model}`])); + await saveLocalModels({ [`${id}Url`]: base, bindings: freeClasses(text) }); return setupOutcome(); } diff --git a/apps/runtime/src/routes/model-setup.ts b/apps/runtime/src/routes/model-setup.ts index 142ef2ee..3cd906da 100644 --- a/apps/runtime/src/routes/model-setup.ts +++ b/apps/runtime/src/routes/model-setup.ts @@ -6,6 +6,7 @@ import { generateText } from "ai"; import { z } from "zod"; import { env } from "../env.js"; import { clientSetup, HARNESS_IDS } from "../harness/index.js"; +import { localServers } from "../local-models.js"; import { DECISION_CHOICES, EMBEDDING_CHOICES, @@ -14,7 +15,7 @@ import { localModelSettings, saveLocalModels, setUpKey, - setUpOllama, + setUpServer, textModel, } from "../models.js"; import { ServiceError } from "../services/errors.js"; @@ -31,6 +32,7 @@ export const modelsInput = z.object({ source: z.enum([...HARNESS_IDS, "account", "own"]).optional(), bindings: z.partialRecord(z.enum(MODEL_CLASSES), z.string().max(160)).optional(), ollamaUrl: z.string().max(200).optional(), + lmstudioUrl: z.string().max(200).optional(), creditFallback: z.boolean().optional(), decision: z.enum(DECISION_CHOICES).optional(), embedding: z.enum(EMBEDDING_CHOICES).optional(), @@ -53,6 +55,7 @@ export const localSetup = setupRoutes({ terminals: new Terminals(), workDir: () => join(env.dataDir, "harness"), tested: testedSources, + servers: localServers, models: { source: () => localModelSettings().source, settings: () => localModelSettings(), @@ -72,7 +75,7 @@ export const localSetup = setupRoutes({ }, providers: LOCAL_KEYS, key: (c, provider, key) => setUpKey(provider as LocalKey, key, requestLang(c)), - ollama: (c, url) => setUpOllama(url, requestLang(c)), + server: (c, id, url) => setUpServer(id, url, requestLang(c)), }, }); diff --git a/apps/runtime/src/routes/studio.ts b/apps/runtime/src/routes/studio.ts index 26dbac40..da806fe2 100644 --- a/apps/runtime/src/routes/studio.ts +++ b/apps/runtime/src/routes/studio.ts @@ -87,12 +87,6 @@ import { wizardsView, wizardView, } from "../live/views.js"; -import { - downloadLocalModel, - localModels, - removeLocalModel, - startLocalOllama, -} from "../local-models.js"; import { installMail, ManageError, @@ -363,14 +357,6 @@ async function setupDone(): Promise { return hasTextModel(); } -/** A model as Ollama names it: `name`, `name:tag`, `namespace/name:tag` or `hf.co/…`. */ -const localModelName = z - .string() - .trim() - .min(1) - .max(120) - .regex(/^[\w.:/-]+$/); - /** The Manage-App's masking errors, passed on as it sends them: 502 labels, 503 the detector. */ const MASKING_CODES = new Set(["labels_unavailable", "masking_unavailable"]); @@ -2145,6 +2131,7 @@ export const studio = new Hono() managed && (input.source || input.ollamaUrl || + input.lmstudioUrl || Object.values(input.bindings ?? {}).some((ref) => ref && !cloudBinding(ref))) ) { return c.json( @@ -2287,49 +2274,6 @@ export const studio = new Hono() } }) // Ollama on this computer: its models, what each can do, the ones to download, the downloads. - .get("/models/local", async (c) => { - if (managed) { - return c.notFound(); - } - return c.json(await localModels()); - }) - // A model pulled into Ollama. Where it is the embedding model now, the spaces are indexed with it after. - .post("/models/local/pull", async (c) => { - if (managed || !mayChangeModels(c.get("user"))) { - return c.notFound(); - } - const { model } = z.object({ model: localModelName }).parse(await c.req.json()); - const embeddedBy = (await embeddingModel().catch(() => null))?.ref ?? null; - await downloadLocalModel(model, async () => { - if (((await embeddingModel().catch(() => null))?.ref ?? null) !== embeddedBy) { - await reindexAll(); - } - }); - return c.json(await localModels()); - }) - .delete("/models/local", async (c) => { - if (managed || !mayChangeModels(c.get("user"))) { - return c.notFound(); - } - const model = localModelName.parse(c.req.query("model")); - try { - await removeLocalModel(model); - } catch (err) { - return c.json( - { error: say(c, "localModelNotRemoved", { error: (err as Error).message }) }, - 400, - ); - } - return c.json(await localModels()); - }) - // Ollama installed (on a Mac) and started, as `wizards setup` does. - .post("/models/local/ollama", async (c) => { - if (managed || !mayChangeModels(c.get("user"))) { - return c.notFound(); - } - await startLocalOllama(); - return c.json(await localModels()); - }) // The organization's own accounts at the providers, kept by the Manage-App (`ownKeysGateway`). .get("/models/keys", listKeys) .post("/models/keys", addKey) diff --git a/apps/runtime/src/texts.ts b/apps/runtime/src/texts.ts index 935f0b11..d091b129 100644 --- a/apps/runtime/src/texts.ts +++ b/apps/runtime/src/texts.ts @@ -11,8 +11,8 @@ const EN = { schemaMismatch: "The wizard doesn’t match the schema.", providerError: "The provider answered with error {status}.", providerUnreachable: "The provider cannot be reached right now.", - ollamaUnreachable: "Nothing answers at this address. Is Ollama running?", - ollamaNoModel: "Ollama runs, but has no model yet: `ollama pull qwen3` fetches one.", + serverUnreachable: "Nothing answers at this address. Is {name} running?", + serverNoModel: "{name} runs, but has no model that writes yet.", importedFrom: "Imported from “{name}”: {steps}, {files}.", imported: "Imported: {steps}, {files}.", stepCount: { one: "{count} step", other: "{count} steps" }, @@ -125,7 +125,6 @@ const EN = { somethingWentWrongTry: "Something went wrong. Try again.", unknownApp: "Unknown app.", onlyOrganizationAdminsChange: "Only organization admins can change its models.", - localModelNotRemoved: "Ollama didn’t remove the model: {error}", modelLacksForClass: "{model} lacks what the class {cls} can’t work without: {needs}. Choose another model for it.", "need.tools": "tool calls", @@ -309,8 +308,8 @@ const DE: Partial> = { keyUnknown: "Der Anbieter kennt diesen API-Key nicht.", providerError: "Der Anbieter antwortet mit Fehler {status}.", providerUnreachable: "Der Anbieter ist gerade nicht erreichbar.", - ollamaUnreachable: "Unter dieser Adresse antwortet nichts. Läuft Ollama?", - ollamaNoModel: "Ollama läuft, hat aber noch kein Modell: `ollama pull qwen3` holt eines.", + serverUnreachable: "Unter dieser Adresse antwortet nichts. Läuft {name}?", + serverNoModel: "{name} läuft, hat aber noch kein Modell, das schreibt.", importedFrom: "Importiert aus „{name}“: {steps}, {files}.", imported: "Importiert: {steps}, {files}.", stepCount: { one: "{count} Schritt", other: "{count} Schritte" }, @@ -413,7 +412,6 @@ const DE: Partial> = { somethingWentWrongTry: "Da ist etwas schiefgelaufen. Versuch es noch einmal.", unknownApp: "Diese App gibt es nicht.", onlyOrganizationAdminsChange: "Nur Admins der Organisation ändern ihre Modelle.", - localModelNotRemoved: "Ollama hat das Modell nicht entfernt: {error}", modelLacksForClass: "{model} fehlt, was die Klasse {cls} unbedingt braucht: {needs}. Wähle dafür ein anderes Modell.", "need.tools": "Tool-Aufrufe", diff --git a/apps/runtime/test/harness.test.ts b/apps/runtime/test/harness.test.ts index ee21a380..51b3a5ec 100644 --- a/apps/runtime/test/harness.test.ts +++ b/apps/runtime/test/harness.test.ts @@ -26,7 +26,7 @@ describe("an installed AI client as a model", () => { }); it("reads the result Antigravity prints after its step events", async () => { - const { antigravityAnswer } = await import("../src/harness/antigravity"); + const { antigravityAnswer } = await import("@engenty/local-models/clients"); const r = antigravityAnswer( [ '{"event":"init","conversation_id":"a1","init":{"tools":[]}}', @@ -41,7 +41,7 @@ describe("an installed AI client as a model", () => { }); it("puts the instructions in front of the one message Antigravity reads", async () => { - const { antigravityMessage, withEffort } = await import("../src/harness/antigravity"); + const { antigravityMessage, withEffort } = await import("@engenty/local-models/clients"); const line = antigravityMessage("Be brief.", "Hi"); expect(JSON.parse(line)).toEqual({ event: "user", diff --git a/apps/runtime/test/local-models.test.ts b/apps/runtime/test/local-models.test.ts index c638bbbc..02ecf4b1 100644 --- a/apps/runtime/test/local-models.test.ts +++ b/apps/runtime/test/local-models.test.ts @@ -84,9 +84,14 @@ beforeAll(async () => { afterAll(() => server.close()); describe("the models in Ollama on this computer", () => { + let ollama: (typeof local.localServers)[number]; + beforeAll(() => { + [ollama] = local.localServers; + }); + it("sorts them by job from what Ollama says each can do", async () => { - const state = await local.localModels(); - expect(state.ollama.version).toBe("0.40.12"); + const state = await ollama.state(); + expect(state.server).toMatchObject({ id: "ollama", running: true, version: "0.40.12" }); const byName = Object.fromEntries(state.installed.map((m) => [m.name, m])); expect(byName["embeddinggemma-2:740m"]).toMatchObject({ jobs: ["search"], @@ -100,7 +105,7 @@ describe("the models in Ollama on this computer", () => { }); it("offers the Manage-App's models, marked as there and as fitting this computer", async () => { - const { offered } = await local.localModels(); + const { offered } = await ollama.state(); const byName = Object.fromEntries((offered ?? []).map((m) => [m.name, m])); expect(Object.keys(byName)).toEqual([ "qwen3.8:27b", @@ -116,9 +121,9 @@ describe("the models in Ollama on this computer", () => { }); it("removes a model, and says Ollama's reason where it refuses", async () => { - await local.removeLocalModel("qwen3.8:27b-mlx"); + await ollama.remove("qwen3.8:27b-mlx"); expect(deleted).toEqual(["qwen3.8:27b-mlx"]); - await expect(local.removeLocalModel("nothing:here")).rejects.toThrow( + await expect(ollama.remove("nothing:here")).rejects.toThrow( "model 'nothing:here' not found", ); }); diff --git a/apps/runtime/test/setup-keys.test.ts b/apps/runtime/test/setup-keys.test.ts index 8b5f73ad..61451825 100644 --- a/apps/runtime/test/setup-keys.test.ts +++ b/apps/runtime/test/setup-keys.test.ts @@ -38,7 +38,14 @@ beforeAll(async () => { if (!net.ollama) { throw new Error("ECONNREFUSED"); } - return new Response(JSON.stringify({ data: net.ollama.map((id) => ({ id })) })); + const models = net.ollama.map((name) => ({ name, size: 1e9, digest: name })); + return Response.json( + String(url).endsWith("/api/version") + ? { version: "0.40.12" } + : String(url).endsWith("/api/show") + ? { capabilities: ["completion"] } + : { models }, + ); } return new Response("{}", { status: net.status }); }), @@ -101,7 +108,7 @@ describe("the setup's test of a key", () => { describe("the setup's test of Ollama", () => { it("binds the text classes to the first model Ollama has", async () => { net.ollama = ["llama3.2", "qwen3"]; - const result = await models.setUpOllama("http://127.0.0.1:11434/v1/"); + const result = await models.setUpServer("ollama", "http://127.0.0.1:11434/v1/"); expect(result).toEqual({ ok: true, message: null, text: "ollama:llama3.2" }); expect(bindings().high).toBe("ollama:llama3.2"); expect(models.localModelSettings().ollamaUrl).toBe("http://127.0.0.1:11434/v1"); @@ -109,9 +116,9 @@ describe("the setup's test of Ollama", () => { it("says so when Ollama has no model or does not answer", async () => { net.ollama = []; - expect((await models.setUpOllama("http://127.0.0.1:11434/v1")).ok).toBe(false); + expect((await models.setUpServer("ollama", "http://127.0.0.1:11434/v1")).ok).toBe(false); net.ollama = null; - expect((await models.setUpOllama("http://127.0.0.1:11434/v1")).ok).toBe(false); + expect((await models.setUpServer("ollama", "http://127.0.0.1:11434/v1")).ok).toBe(false); expect(bindings().low).toBe(""); }); }); diff --git a/apps/web/src/lib/i18n.ts b/apps/web/src/lib/i18n.ts index aa78f04d..57b80393 100644 --- a/apps/web/src/lib/i18n.ts +++ b/apps/web/src/lib/i18n.ts @@ -277,10 +277,8 @@ const de: Record = { "models.chatHint": "Mit einem Abo arbeitet das Programm auf diesem Computer, angemeldet mit deinem Konto dort. Es nutzt dabei nur die Werkzeuge von engenty wizards. Für Läufe gilt, was unter „In Läufen“ eingestellt ist.", "models.groupAccess": "Zugänge", - "models.cap.text": "Text & Denken", "models.cap.text.hint": "Schreibt, fasst zusammen, recherchiert und entscheidet – in fast jedem Schritt.", - "models.cap.decision": "Entscheidungen", "models.cap.decision.hint": "Beantwortet Fragen mit Ja oder Nein, einer Auswahl oder einer Stufe: welcher Weg im Wizard, ob ein Treffer passt.", "models.decisionModelGroup": "Entscheidungsmodell", @@ -304,7 +302,6 @@ const de: Record = { "models.decisionFallbackWay": "Classifier: {way}", "models.decisionOpenText": "Text & Denken öffnen", "models.decisionByLlm": "Sprachmodell", - "models.cap.search": "Wissen durchsuchen", "models.cap.search.hint": "Findet im Wissen eines Space, was ein Schritt braucht, auch wenn dort andere Wörter stehen.", "models.searchModelGroup": "Embedding-Modell", @@ -316,50 +313,20 @@ const de: Record = { "models.searchCloudHint": "In der Cloud rechnet das Guthaben der Organisation die Vektoren.", "models.searchLocalHint": "{model} fehlt in Ollama.", "models.searchLocalReady": "{model} läuft in Ollama auf diesem Computer. Nichts verlässt ihn.", - "models.ollamaAddress": "Adresse von Ollama", - "models.ollamaOpen": "Ollama öffnen", - "models.ollamaLead": + "models.serverAddress": "Adresse von {name}", + "models.serverOpen": "{name} öffnen", + "models.serverLead.ollama": "Modelle auf diesem Computer für Text, Suche und Entscheidungen: kostenlos, und nichts verlässt ihn.", - "models.ollamaRuns": "Ollama {version}", - "models.ollamaStoppedShort": "läuft nicht", - "models.ollamaMissingShort": "nicht installiert", - "models.ollamaModels": "Modelle", - "models.ollamaModelsHint": - "Welches Modell eine Aufgabe nimmt, wählst du auf ihrer Seite: Text & Denken, Suche, Entscheidungen.", - "models.ollamaAddressHint": + "models.serverLead.lmstudio": + "Modelle auf diesem Computer für Text: kostenlos, und nichts verlässt ihn.", + "models.serverStoppedShort": "läuft nicht", + "models.serverMissingShort": "nicht installiert", + "models.serverModels": "Modelle", + "models.serverModelsHint": "Welches Modell eine Aufgabe nimmt, wählst du auf ihrer Seite.", + "models.serverAddressHint.ollama": "Wo Ollama antwortet. Auf diesem Computer ist das http://127.0.0.1:11434/v1.", - "models.local.downloadOnly": "Laden", - "models.local.noOllama": "Ollama ist nicht auf diesem Computer. Lokale Modelle laufen darüber.", - "models.local.ollamaStopped": "Ollama ist installiert, läuft aber nicht.", - "models.local.installOllama": "Ollama installieren", - "models.local.startOllama": "Ollama starten", - "models.local.ollamaStarting": - "Ollama startet. Auf einem Mac fragt es eventuell einmal nach deinem Passwort.", - "models.local.ollamaFailed": "Ollama ist nicht gestartet: {error}", - "models.local.ollamaLinux": "Installiere Ollama in einem Terminal:", - "models.local.here": "Auf diesem Computer · Ollama {version}", - "models.local.hereNone": "Noch kein Modell dafür.", - "models.local.offered": "Zum Laden", - "models.local.offeredNone": "Die Liste der Modelle zum Laden ist gerade nicht erreichbar.", - "models.local.other": "Ein anderes Modell aus Ollama", - "models.local.otherPlaceholder": "z. B. llama3.2:3b", - "models.local.use": "Verwenden", - "models.local.inUse": "in Verwendung", - "models.local.download": "Laden und verwenden", - "models.local.starting": "Lädt …", - "models.local.progress": "{done} von {total} MB", - "models.local.downloadNoOllama": - "Ollama läuft nicht auf diesem Computer. Starte es und versuch es noch einmal.", - "models.local.downloadFailed": "Das Laden hat nicht geklappt: {error}", - "models.local.remove": "Aus Ollama entfernen", - "models.local.removeConfirm": "„{name}“ aus Ollama entfernen? Das gibt {size} GB frei.", - "models.local.size": "{size} GB", - "models.local.suggested": "empfohlen", - "models.local.tooBig": "braucht etwa {memory} GB Arbeitsspeicher", - "models.local.loaded": "geladen", - "models.local.cap.vision": "Bilder", - "models.local.cap.audio": "Ton", - "models.local.cap.tools": "Werkzeuge", + "models.serverAddressHint.lmstudio": + "Wo LM Studio antwortet. Auf diesem Computer ist das http://127.0.0.1:1234/v1.", "models.searchFallback": "Ohne Embedding-Modell", "models.searchFallbackHint": "Steht keins bereit oder antwortet es nicht, sucht die Suche nur nach Wörtern. Sie findet dann „Rechnung“, aber nicht „Beleg“.", @@ -381,7 +348,7 @@ const de: Record = { "models.optSubscription": "Dein Abo", "models.optKey": "Eigener API-Key", "models.optLocal": "Lokales Modell", - "models.optLocalNote": "Ollama auf diesem Computer", + "models.optLocalNote": "auf diesem Computer", "models.optApple": "Apple Intelligence", "models.optAppleNote": "auf diesem Mac, ohne Internet", "models.appleOff": "ausgeschaltet – Systemeinstellungen → Apple Intelligence & Siri", @@ -472,8 +439,8 @@ const de: Record = { "models.clientSignIn": "Anmeldung", "models.clientImages": "{name} erzeugt Bilder mit deinem {sub} – ohne eigenen API-Key.", "models.clientNotChosen": "Text läuft gerade nicht über {name}.", - "models.ollamaHint": - "Modelle in Ollama auf diesem Computer: kostenlos, und nichts verlässt ihn. Das gewählte Modell denkt für alle Klassen von Text & Denken.", + "models.serverHint": + "Modelle in {name} auf diesem Computer: kostenlos, und nichts verlässt ihn. Das gewählte Modell denkt für alle Klassen von Text & Denken.", "models.readOnly": "Nur Admins der Organisation ändern die Modelle.", "models.viewAs": "Vorschau als", "models.view.auto": "aktuell", @@ -557,10 +524,11 @@ const de: Record = { "overview.client.key": "mit API-Key", "overview.client.signIn": "Anmelden", "overview.apple.desc": "Das Modell auf diesem Mac, ohne Internet.", - "overview.ollama.desc": + "overview.server.desc.ollama": "Modelle auf diesem Computer, ohne Internet. Für Entscheidungen und Wissen.", - "overview.ollama.one": "1 Modell", - "overview.ollama.n": "{n} Modelle", + "overview.server.desc.lmstudio": "Modelle auf diesem Computer, ohne Internet. Für Text.", + "overview.server.one": "1 Modell", + "overview.server.n": "{n} Modelle", "overview.keys.add": "Hinzufügen", "overview.keys.fromEnv": "Aus der Umgebungsvariable {env} auf diesem Computer.", "overview.keys.kept": "Im Studio gespeichert, verschlüsselt auf diesem Computer.", @@ -826,7 +794,7 @@ const de: Record = { "onboard.sectorHint": "Danach wählt das Studio deine Vorlagen:", "onboard.catalog": "Wizards für {sector}", "onboard.step": "Schritt {n} von {total}", - "setup.ownDesc": "OpenAI, Anthropic, Google, AI Gateway oder Ollama.", + "setup.ownDesc": "OpenAI, Anthropic, Google oder AI Gateway.", "setup.appleDesc": "Das Modell auf diesem Mac – ohne Konto, ohne Internet.", "setup.appleHint": "Kurze Texte und Entscheidungen übernimmt Apple Intelligence auf diesem Mac. Nichts verlässt ihn. Für Recherche, lange Dokumente und Code richtest du später unter Einstellungen → Modelle einen weiteren Zugang ein.", @@ -5343,9 +5311,7 @@ const en = { "models.chatHint": "With a subscription, the program works on this computer, using your sign-in there. It uses only the tools of engenty wizards. Runs use what is set under “In runs”.", "models.groupAccess": "Access", - "models.cap.text": "Text & reasoning", "models.cap.text.hint": "Writes, summarises, researches and decides – in almost every step.", - "models.cap.decision": "Decisions", "models.cap.decision.hint": "Answers questions with yes or no, a choice or a level: which way a wizard goes, whether a hit fits.", "models.decisionModelGroup": "Decision model", @@ -5369,7 +5335,6 @@ const en = { "models.decisionFallbackWay": "Classifier: {way}", "models.decisionOpenText": "Open Text & reasoning", "models.decisionByLlm": "language model", - "models.cap.search": "Knowledge search", "models.cap.search.hint": "Finds what a step needs in a space’s knowledge, even where other words are used.", "models.searchModelGroup": "Embedding model", @@ -5381,48 +5346,19 @@ const en = { "models.searchCloudHint": "In the cloud, the organization’s credits pay for the vectors.", "models.searchLocalHint": "Ollama doesn’t have {model}.", "models.searchLocalReady": "{model} runs in Ollama on this computer. Nothing leaves it.", - "models.ollamaAddress": "Ollama’s address", - "models.ollamaOpen": "Open Ollama", - "models.ollamaLead": + "models.serverAddress": "{name}’s address", + "models.serverOpen": "Open {name}", + "models.serverLead.ollama": "Models on this computer for text, search and decisions: free, and nothing leaves it.", - "models.ollamaRuns": "Ollama {version}", - "models.ollamaStoppedShort": "not running", - "models.ollamaMissingShort": "not installed", - "models.ollamaModels": "Models", - "models.ollamaModelsHint": - "Which model a job takes, you choose on its page: Text & reasoning, Search, Decisions.", - "models.ollamaAddressHint": + "models.serverLead.lmstudio": "Models on this computer for text: free, and nothing leaves it.", + "models.serverStoppedShort": "not running", + "models.serverMissingShort": "not installed", + "models.serverModels": "Models", + "models.serverModelsHint": "Which model a job takes, you choose on its page.", + "models.serverAddressHint.ollama": "Where Ollama answers. On this computer that is http://127.0.0.1:11434/v1.", - "models.local.downloadOnly": "Download", - "models.local.noOllama": "Ollama isn’t on this computer. Local models run through it.", - "models.local.ollamaStopped": "Ollama is installed but isn’t running.", - "models.local.installOllama": "Install Ollama", - "models.local.startOllama": "Start Ollama", - "models.local.ollamaStarting": "Ollama is starting. On a Mac it may ask for your password once.", - "models.local.ollamaFailed": "Ollama didn’t start: {error}", - "models.local.ollamaLinux": "Install Ollama in a terminal:", - "models.local.here": "On this computer · Ollama {version}", - "models.local.hereNone": "No model for this yet.", - "models.local.offered": "To download", - "models.local.offeredNone": "The list of models to download isn’t reachable right now.", - "models.local.other": "Another model from Ollama", - "models.local.otherPlaceholder": "e.g. llama3.2:3b", - "models.local.use": "Use", - "models.local.inUse": "in use", - "models.local.download": "Download and use", - "models.local.starting": "Loading…", - "models.local.progress": "{done} of {total} MB", - "models.local.downloadNoOllama": "Ollama isn’t running on this computer. Start it and try again.", - "models.local.downloadFailed": "The download didn’t work: {error}", - "models.local.remove": "Remove from Ollama", - "models.local.removeConfirm": "Remove “{name}” from Ollama? This frees {size} GB.", - "models.local.size": "{size} GB", - "models.local.suggested": "suggested", - "models.local.tooBig": "needs about {memory} GB memory", - "models.local.loaded": "loaded", - "models.local.cap.vision": "images", - "models.local.cap.audio": "sound", - "models.local.cap.tools": "tools", + "models.serverAddressHint.lmstudio": + "Where LM Studio answers. On this computer that is http://127.0.0.1:1234/v1.", "models.searchFallback": "Without an embedding model", "models.searchFallbackHint": "When none is at hand or it doesn’t answer, the search looks for words only. It then finds “invoice” but not “receipt”.", @@ -5444,7 +5380,7 @@ const en = { "models.optSubscription": "Your subscription", "models.optKey": "Your own API key", "models.optLocal": "Local model", - "models.optLocalNote": "Ollama on this computer", + "models.optLocalNote": "on this computer", "models.optApple": "Apple Intelligence", "models.optAppleNote": "on this Mac, offline", "models.appleOff": "switched off – System Settings → Apple Intelligence & Siri", @@ -5536,8 +5472,8 @@ const en = { "models.clientSignIn": "Sign-in", "models.clientImages": "{name} makes images with your {sub} – no API key of your own.", "models.clientNotChosen": "Text doesn’t run on {name} right now.", - "models.ollamaHint": - "Models in Ollama on this computer: free, and nothing leaves it. The model you pick thinks for every class of Text & reasoning.", + "models.serverHint": + "Models in {name} on this computer: free, and nothing leaves it. The model you pick thinks for every class of Text & reasoning.", "models.readOnly": "Only the organization’s admins can change its models.", "models.viewAs": "Preview as", "models.view.auto": "as it is", @@ -5618,9 +5554,10 @@ const en = { "overview.client.key": "with an API key", "overview.client.signIn": "Sign in", "overview.apple.desc": "The model on this Mac, offline.", - "overview.ollama.desc": "Models on this computer, offline. For decisions and knowledge.", - "overview.ollama.one": "1 model", - "overview.ollama.n": "{n} models", + "overview.server.desc.ollama": "Models on this computer, offline. For decisions and knowledge.", + "overview.server.desc.lmstudio": "Models on this computer, offline. For text.", + "overview.server.one": "1 model", + "overview.server.n": "{n} models", "overview.keys.add": "Add", "overview.keys.fromEnv": "From the environment variable {env} on this computer.", "overview.keys.kept": "Kept in the studio, encrypted on this computer.", @@ -5877,7 +5814,7 @@ const en = { "onboard.sectorHint": "The studio picks your templates by it:", "onboard.catalog": "Wizards for {sector}", "onboard.step": "Step {n} of {total}", - "setup.ownDesc": "OpenAI, Anthropic, Google, AI Gateway or Ollama.", + "setup.ownDesc": "OpenAI, Anthropic, Google or AI Gateway.", "setup.appleDesc": "The model on this Mac – no account, no internet.", "setup.appleHint": "Apple Intelligence handles short texts and decisions on this Mac; nothing leaves it. For research, long documents and code, add another option later under Settings → Models.", diff --git a/apps/web/src/lib/session.ts b/apps/web/src/lib/session.ts index c1816329..318b81e1 100644 --- a/apps/web/src/lib/session.ts +++ b/apps/web/src/lib/session.ts @@ -53,6 +53,8 @@ export type HarnessId = "claude" | "codex" | "antigravity" | "cursor"; export interface HarnessStatus { id: HarnessId; name: string; + /** The name with its provider, where a list shows it. */ + label: string; /** How to install it in a terminal; the setup's Install button runs the same command. */ install: string; /** The vendor's desktop app on this machine ("Claude"): the subscription is most likely there. */ @@ -71,6 +73,7 @@ export interface LocalModels { source: HarnessId | "account" | "own"; bindings: Record; ollamaUrl: string; + lmstudioUrl: string; /** Which providers have a key stored, by provider id. */ keys: Partial>; } diff --git a/apps/web/src/studio/LocalModels.tsx b/apps/web/src/studio/LocalModels.tsx index 97e6dedd..67c118e0 100644 --- a/apps/web/src/studio/LocalModels.tsx +++ b/apps/web/src/studio/LocalModels.tsx @@ -1,185 +1,46 @@ -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { Trash2 } from "lucide-react"; -import { type ReactNode, useEffect, useState } from "react"; +import type { LocalModelsState, ModelJob, ServerStatus } from "@engenty/model-setup"; +import { modelsMoving, LocalModels as SetupLocalModels } from "@engenty/model-setup/react"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { useEffect } from "react"; import { api } from "../lib/api"; -import { lang, t } from "../lib/i18n"; -import { askConfirm, Button, cn, Input } from "../ui"; +import { StudioSetup } from "./Harness"; /** What a model does in the studio: a text class, the search of a space's knowledge, decisions. */ -const LOCAL_JOBS = ["text", "search", "decision"] as const; -export type LocalJob = (typeof LOCAL_JOBS)[number]; +export type LocalJob = ModelJob; -/** A job, by the name of its page. */ -const JOB_LABEL = { - text: "models.cap.text", - search: "models.cap.search", - decision: "models.cap.decision", -} as const satisfies Record; +/** A server for open models on this computer. */ +export type ServerId = ServerStatus["id"]; -interface InstalledModel { - name: string; - size: number; - jobs: LocalJob[]; - capabilities: string[]; - runner: string | null; - quantization: string | null; - loaded: boolean; -} - -interface OfferedModel { - name: string; - job: LocalJob; - size: number; - memory: number; - note: { en: string; de: string }; - installed: boolean; - fits: boolean; -} - -interface LocalDownload { - model: string; - done: number; - total: number; - /** `ollama`: Ollama does not run on this computer; else what Ollama said. */ - error: string | null; - finished: boolean; -} - -/** `GET /api/studio/models/local`: Ollama on this computer, its models, the ones to download. */ -interface LocalModelsState { - ollama: { - url: string; - version: string | null; - installed: boolean; - canInstall: boolean; - start: { running: boolean; error: string | null } | null; - }; - memory: number; - free: number | null; - installed: InstalledModel[]; - offered: OfferedModel[] | null; - downloads: LocalDownload[]; -} - -const LINUX_INSTALL = "curl -fsSL https://ollama.com/install.sh | sh"; - -/** What a model can do beyond its job, as chips. */ -const CAP_CHIPS = ["vision", "audio", "tools"] as const; - -const mb = (bytes: number) => Math.round(bytes / 1e6).toLocaleString(lang); -const gb = (n: number) => n.toLocaleString(lang, { maximumFractionDigits: 1 }); - -/** Ollama names a model without a tag as `name:latest`. */ -const sameModel = (a: string, b: string) => a === b || a === `${b}:latest` || `${a}:latest` === b; - -function Chip({ children, tone }: { children: ReactNode; tone?: "done" }) { - return ( - - {children} - - ); -} - -function Group({ title, children }: { title: string; children: ReactNode }) { - return ( -
- {title} -
- {children} -
-
- ); -} +const keyOf = (server: ServerId) => ["models", "local", server]; -function Row({ children, actions }: { children: ReactNode; actions: ReactNode }) { - return ( -
-
{children}
-
{actions}
-
- ); -} - -function DownloadState({ download }: { download: LocalDownload }) { - if (download.error) { - return ( -

- {download.error === "ollama" - ? t("models.local.downloadNoOllama") - : t("models.local.downloadFailed", { error: download.error })} -

- ); - } - return ( - - {download.total - ? t("models.local.progress", { done: mb(download.done), total: mb(download.total) }) - : t("models.local.starting")} - - ); -} - -/** Ollama on this computer, as `GET /api/studio/models/local` tells it; off where `enabled` is false. */ -export function useLocalModels(enabled = true) { +/** A server on this computer, its models and the ones to download; off where `enabled` is false. */ +export function useLocalModels(server: ServerId, enabled = true) { return useQuery({ - queryKey: ["models", "local"], - queryFn: () => api.get("/api/studio/models/local"), + queryKey: keyOf(server), + queryFn: () => api.get(`/api/studio/local/servers/${server}`), enabled, - // While a download runs or Ollama starts, the page asks how far it got. - refetchInterval: (q) => - q.state.data?.downloads.some((d) => !d.finished) || q.state.data?.ollama.start?.running - ? 1500 - : false, + // While a download runs or the server starts, the page asks how far it got. + refetchInterval: (q) => (modelsMoving(q.state.data) ? 1500 : false), }); } -/** - * The models in Ollama on this computer. For one job: the ones there (to use or remove), the - * ones the Manage-App offers (to download and use), and any other name from Ollama. Without a - * job, all of them with the jobs each serves, to download or remove. Where Ollama does not - * run, a way to start it — or to install it, on a Mac. - */ +/** The models of a server on this computer, as the setup lists them (@engenty/model-setup). */ export function LocalModels({ - job, - inUse, - disabled, - onChoose, + server, + ...props }: { + server: ServerId; /** Absent: every job, and nothing to choose. */ job?: LocalJob; /** The models the studio asks for now; they are not removed. */ inUse: string[]; disabled?: boolean; onChoose?: (model: string) => void; + /** Only a model that is there is chosen; a download only downloads. */ + onlyHeld?: boolean; }) { const qc = useQueryClient(); - const [other, setOther] = useState(""); - const [removeError, setRemoveError] = useState(null); - const { data: state } = useLocalModels(); - const set = (next: LocalModelsState) => qc.setQueryData(["models", "local"], next); - const pull = useMutation({ - mutationFn: (model: string) => - api.post("/api/studio/models/local/pull", { model }), - onSuccess: set, - }); - const remove = useMutation({ - mutationFn: (model: string) => - api.del(`/api/studio/models/local?model=${encodeURIComponent(model)}`), - onSuccess: (next) => { - setRemoveError(null); - set(next); - }, - onError: (err) => setRemoveError((err as Error).message), - }); - const start = useMutation({ - mutationFn: () => api.post("/api/studio/models/local/ollama", {}), - onSuccess: set, - }); + const { data: state } = useLocalModels(server); // A model that arrived or went changes which ways are ready. const held = state?.installed.map((m) => m.name).join(" "); useEffect(() => { @@ -187,199 +48,13 @@ export function LocalModels({ void qc.invalidateQueries({ queryKey: ["models"], exact: true }); } }, [held, qc]); - - if (!state) { - return null; - } - const { ollama } = state; - if (!ollama.version) { - const starting = Boolean(ollama.start?.running) || start.isPending; - return ( -
-

- {ollama.installed ? t("models.local.ollamaStopped") : t("models.local.noOllama")} -

- {ollama.installed || ollama.canInstall ? ( -
- - {starting ? ( - - {t("models.local.ollamaStarting")} - - ) : null} -
- ) : ( -

- {t("models.local.ollamaLinux")}{" "} - {LINUX_INSTALL} -

- )} - {ollama.start?.error ? ( -

- {t("models.local.ollamaFailed", { error: ollama.start.error })} -

- ) : null} -
- ); - } - - const downloadOf = (model: string) => state.downloads.find((d) => sameModel(d.model, model)); - const use = (model: string) => { - if (!state.installed.some((m) => sameModel(m.name, model))) { - pull.mutate(model); - } - onChoose?.(model); - }; - const here = job ? state.installed.filter((m) => m.jobs.includes(job)) : state.installed; - const offered = - state.offered?.filter((m) => (job ? m.job === job : true) && !m.installed) ?? null; - // Per job, the first one that fits this computer. - const suggested = new Set( - LOCAL_JOBS.map((j) => offered?.find((m) => m.job === j && m.fits)?.name), - ); - // Downloads of names from the free field, which no list shows. - const others = state.downloads.filter( - (d) => - !(here.some((m) => sameModel(m.name, d.model)) || offered?.some((m) => m.name === d.model)), - ); - return ( -
- - {here.length ? ( - here.map((m) => { - const used = inUse.some((name) => sameModel(m.name, name)); - return ( - - {used ? ( - {t("models.local.inUse")} - ) : !onChoose ? null : ( - - )} - - - } - > - {m.name} - - {job ? null : m.jobs.map((j) => {t(JOB_LABEL[j])})} - {t("models.local.size", { size: gb(m.size) })} - {m.runner === "mlx" ? MLX : null} - {CAP_CHIPS.filter((c) => m.capabilities.includes(c)).map((c) => ( - {t(`models.local.cap.${c}`)} - ))} - {m.loaded ? {t("models.local.loaded")} : null} - - - ); - }) - ) : ( -

{t("models.local.hereNone")}

- )} -
- {removeError ?

{removeError}

: null} - - {offered === null ? ( -

{t("models.local.offeredNone")}

- ) : offered.length ? ( - - {offered.map((m) => { - const download = downloadOf(m.name); - const running = Boolean(download && !download.finished); - return ( - - ) : ( - - ) - } - > - - {m.name} - {suggested.has(m.name) ? ( - {t("models.local.suggested")} - ) : null} - - - {m.note[lang === "de" ? "de" : "en"]} - - - {job ? null : {t(JOB_LABEL[m.job])}} - {t("models.local.size", { size: gb(m.size) })} - {m.fits ? null : ( - {t("models.local.tooBig", { memory: gb(m.memory) })} - )} - - {download?.error ? : null} - - ); - })} - - ) : null} - -
- {t("models.local.other")} -
{ - e.preventDefault(); - use(other.trim()); - setOther(""); - }} - > - setOther(e.target.value)} - /> - -
- {others.map((d) => ( - - {d.model} - - - ))} -
-
+ + qc.setQueryData(keyOf(server), next)} + /> + ); } diff --git a/apps/web/src/studio/LocalRuntime.tsx b/apps/web/src/studio/LocalRuntime.tsx index 0a873d1c..f0627e70 100644 --- a/apps/web/src/studio/LocalRuntime.tsx +++ b/apps/web/src/studio/LocalRuntime.tsx @@ -1,4 +1,4 @@ -import { OllamaAddress, OwnKeys } from "@engenty/model-setup/react"; +import { OwnKeys } from "@engenty/model-setup/react"; import { modelLabel, PROVIDERS, providerOfRef } from "@engenty/wizards-shared/providers"; import { api } from "../lib/api"; import { t } from "../lib/i18n"; @@ -17,7 +17,7 @@ export function openExternal(url: string) { /** The providers that can write: a key from one of them is enough for the setup. */ const WRITERS = PROVIDERS.filter((p) => p.text); -/** The keys of the setup and Ollama. Which model does which job is for Settings → Models. */ +/** The keys of the setup. Which model does which job is for Settings → Models. */ export function OwnModels({ models }: { models: LocalModels }) { return ( api.put("/api/studio/local/models", { keys: { [provider]: "" } })} later={t("local.modelsLater")} - > - - + /> ); } diff --git a/apps/web/src/studio/Models.tsx b/apps/web/src/studio/Models.tsx index 5f8ae17d..5ad9071f 100644 --- a/apps/web/src/studio/Models.tsx +++ b/apps/web/src/studio/Models.tsx @@ -1,3 +1,4 @@ +import type { ServerStatus } from "@engenty/model-setup"; import { type ModelClass, TEXT_CLASSES, type TextClass } from "@engenty/wizards-shared/definition"; import { featureOn } from "@engenty/wizards-shared/features"; import { @@ -65,7 +66,7 @@ import { import { Button, Card, cn, Input, LinkedText, Select, Spinner, Switch } from "../ui"; import { billingUrl } from "./AppFrame"; import { HarnessPanel } from "./Harness"; -import { LocalModels, useLocalModels } from "./LocalModels"; +import { LocalModels, type ServerId, useLocalModels } from "./LocalModels"; import { openExternal } from "./LocalRuntime"; import { AccountPanel, @@ -133,6 +134,7 @@ interface ModelsState { source: HarnessId | "account" | "own"; bindings: Partial>; ollamaUrl: string; + lmstudioUrl: string; creditFallback: boolean; keys: Record; /** Each key there is, masked, and the environment variable it came from (null: kept here). */ @@ -204,13 +206,28 @@ interface AppleStatus { reason: "device" | "os" | "missing" | "off" | "loading" | null; } -/** A model on this machine: Ollama, or Apple Intelligence on a Mac. */ -type LocalBy = "ollama" | "apple"; +/** A model on this machine: a server's, or Apple Intelligence on a Mac. */ +type LocalBy = ServerId | "apple"; + +/** The servers for open models, by the name the person knows and the model text starts with. */ +const SERVERS: Record = { + ollama: { name: "Ollama", first: "qwen3" }, + lmstudio: { name: "LM Studio", first: "google/gemma-4-12b" }, +}; +const SERVER_IDS = Object.keys(SERVERS) as ServerId[]; + +/** A held model's name in a row: Ollama's without the tag that says nothing. */ +const heldName = (model: { name: string }) => model.name.replace(/:latest$/, ""); + +/** The server a binding names. */ +const serverOf = (ref: string | null | undefined) => + SERVER_IDS.find((id) => ref?.startsWith(`${id}:`)); interface ModelsInput { source?: ModelsState["source"]; bindings?: Partial>; ollamaUrl?: string; + lmstudioUrl?: string; creditFallback?: boolean; decision?: DecisionChoice; decisionLocal?: string; @@ -332,8 +349,9 @@ function choiceOf(state: ModelsState, cap: ModelCapability, place: Place): Choic if (isCreditsRef(bound)) { return { kind: "credits" }; } - if (bound?.startsWith("ollama:")) { - return { kind: "local", by: "ollama" }; + const server = serverOf(bound); + if (server) { + return { kind: "local", by: server }; } if (bound?.startsWith("apple:")) { return { kind: "local", by: "apple" }; @@ -352,7 +370,7 @@ function choiceOf(state: ModelsState, cap: ModelCapability, place: Place): Choic case "key": return providerInfo(way.by ?? "") ? { kind: "key", provider: way.by as ProviderId } : null; case "local": - return { kind: "local", by: way.by === "apple" ? "apple" : "ollama" }; + return { kind: "local", by: way.by as LocalBy }; case "credits": return { kind: "credits" }; default: @@ -1009,6 +1027,13 @@ function CapabilityPanel({ (h.version !== null || (chosen?.kind === "client" && chosen.id === h.id)), ); const providers = PROVIDERS.filter((p) => p.models[cap]?.length); + const lmStudio = useLocalModels("lmstudio", isText(cap) && !place.cloud); + const servers = SERVER_IDS.filter( + (id) => + id === "ollama" || + lmStudio.data?.server.installed || + (chosen?.kind === "local" && chosen.by === id), + ); const pick = (next: Choice) => { setNeedsAccount(false); @@ -1041,7 +1066,10 @@ function CapabilityPanel({ save.mutate( next.by === "apple" ? { bindings: isText(cap) ? appleBindings(state) : { audio: "apple:transcribe" } } - : { source: "own", bindings: every("ollama:qwen3") }, + : { + source: "own", + bindings: every(`${next.by}:${SERVERS[next.by].first}`), + }, ); return; case "credits": @@ -1075,7 +1103,7 @@ function CapabilityPanel({ {clients.map((h) => (