Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 4 additions & 16 deletions apps/runtime/src/agents/subscription.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -10,6 +9,7 @@ import {
CLIENTS,
type ClientId,
cursorWorkspace,
ownCursorServers,
resolveEnv,
} from "@engenty/local-models/clients";
import type { Lang } from "@engenty/wizards-shared/definition";
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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()}`;

Expand Down
2 changes: 2 additions & 0 deletions apps/runtime/src/cli/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ const INHERITED = new Set([
"CHROME_PATH",
"FFMPEG_PATH",
"OLLAMA_URL",
"LMSTUDIO_URL",
"LM_API_TOKEN",
"SANDBOX",
"SANDBOX_ENABLED",
"SANDBOX_IMAGE",
Expand Down
199 changes: 1 addition & 198 deletions apps/runtime/src/cli/ollama.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,13 @@
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];

/** 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;
Expand All @@ -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<LocalOllamaState> {
const { version, models } = await ollamaState(ollamaAddress(env));
Expand All @@ -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<number | null> {
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<Outcome> {
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<number>((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<string | null> {
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
Expand Down
24 changes: 11 additions & 13 deletions apps/runtime/src/cli/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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";

Expand Down Expand Up @@ -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);
Expand All @@ -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;
Expand Down
1 change: 1 addition & 0 deletions apps/runtime/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
12 changes: 11 additions & 1 deletion apps/runtime/src/harness/clients.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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/<model>` names one. */
export const cursor = harnessOf(CLIENTS.cursor, {
classes: { classifier: "auto", low: "auto", standard: "auto", high: "auto" },
Expand Down
3 changes: 1 addition & 2 deletions apps/runtime/src/harness/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Loading
Loading