Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Engines the app installed update themselves to this release's tested versions (#4713)
Milind Soni3d4fabca20e2
diff --git a/server/drivers/antigravity-runtime.ts b/server/drivers/antigravity-runtime.tsindex ed6d8fc91a..2e83f18f10 100644--- a/server/drivers/antigravity-runtime.ts+++ b/server/drivers/antigravity-runtime.ts@@ -5,6 +5,7 @@ import {mkdir,mkdtemp,open,+ readdir,readFile,rename,rm,@@ -340,6 +341,21 @@ export function installAntigravityRuntime(options: AntigravityInstallOptions = {return running;}+/** The newest runtime the app installed here, when it is not the pinned one; null when the pinned one is installed or none is. */+export async function antigravityOlderRuntime(baseDir = DATA_DIR, asset = resolveAntigravityReleaseAsset()): Promise<string | null> {+ if (!asset) return null;+ const versions = join(runtimeRoot(baseDir), "versions");+ if (await completedRelease(join(versions, asset.sha256), asset)) return null;+ const found: string[] = [];+ for (const name of await readdir(versions).catch(() => [] as string[])) {+ try {+ const record = JSON.parse(await readFile(join(versions, name, INSTALL_RECORD), "utf8")) as Partial<InstallRecord>;+ if (record.sha256 === name && typeof record.version === "string") found.push(record.version);+ } catch {}+ }+ return found.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))[0] ?? null;+}+export function antigravityManagedInstallAvailable(): boolean {return resolveAntigravityReleaseAsset() !== null;}diff --git a/server/engine-handshake.ts b/server/engine-handshake.tsnew file mode 100644index 0000000000..44bb29f68e--- /dev/null+++ b/server/engine-handshake.ts@@ -0,0 +1,61 @@+import { dirname } from "node:path";+import { stripVTControlCharacters } from "node:util";++import { killCliTree, spawnCli } from "./procs.ts";++export const HANDSHAKE_TIMEOUT_MS = 30_000;+const MAX_LINE_BYTES = 1024 * 1024;++/** Null when `command args` answers an ACP `initialize` with a protocol version; otherwise what went wrong. Nothing is+ * opened beyond that: no session, no prompt. */+export function acpHandshake(command: string, args: readonly string[], env: NodeJS.ProcessEnv, timeoutMs = HANDSHAKE_TIMEOUT_MS): Promise<string | null> {+ return new Promise((resolveHandshake) => {+ let child: ReturnType<typeof spawnCli>;+ try {+ child = spawnCli(command, [...args], { env, cwd: dirname(command), stdio: ["pipe", "pipe", "pipe"] });+ } catch (error) {+ resolveHandshake(error instanceof Error ? error.message : String(error));+ return;+ }+ let settled = false;+ let buffer = "";+ let stderr = "";+ const finish = (failure: string | null) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ void killCliTree(child, 2_000).finally(() => resolveHandshake(failure));+ };+ const timer = setTimeout(() => finish("it did not answer the ACP handshake in time"), timeoutMs);+ timer.unref?.();+ child.once("error", (error) => finish(error.message));+ child.once("exit", (code) => {+ const said = stripVTControlCharacters(stderr).split(/\r?\n/u).map((line) => line.trim()).find(Boolean);+ finish(said ? said.slice(0, 400) : `it stopped with exit code ${code} before the ACP handshake`);+ });+ child.stderr.on("data", (chunk: Buffer) => { if (stderr.length < 8192) stderr += chunk.toString("utf8"); });+ child.stdout.on("data", (chunk: Buffer) => {+ buffer += chunk.toString("utf8");+ if (buffer.length > MAX_LINE_BYTES) return finish("it answered the ACP handshake with too much output");+ for (let newline = buffer.indexOf("\n"); newline >= 0; newline = buffer.indexOf("\n")) {+ const line = buffer.slice(0, newline);+ buffer = buffer.slice(newline + 1);+ let message: { id?: unknown; result?: { protocolVersion?: unknown }; error?: { message?: unknown } };+ try {+ message = JSON.parse(line);+ } catch {+ continue;+ }+ if (message?.id !== 1) continue;+ if (typeof message.result?.protocolVersion === "number") return finish(null);+ return finish(`it refused the ACP handshake${typeof message.error?.message === "string" ? `: ${message.error.message.slice(0, 200)}` : ""}`);+ }+ });+ child.stdin.write(`${JSON.stringify({+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",+ params: { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false } },+ })}\n`);+ });+}diff --git a/server/engine-install.ts b/server/engine-install.tsindex 89aa947dd7..5ed729f91a 100644--- a/server/engine-install.ts+++ b/server/engine-install.ts@@ -1,6 +1,6 @@// No sudo, no shell, no terminal: the package name comes from the driver's own install descriptor, never a request, and// npm runs with a fixed argument list as this process's user into an app-owned prefix.-import { mkdirSync } from "node:fs";+import { mkdirSync, readFileSync } from "node:fs";import { delimiter, join } from "node:path";import { stripVTControlCharacters } from "node:util";import type { EngineInstall, StandaloneRelease } from "./contracts.ts";@@ -12,7 +12,7 @@ import { augmentedPath, findCliCandidates, registerPathDir, resetPathCache } froimport { execCli, killCliTree, spawnCli } from "./procs.ts";const MAX_OUTPUT = 64 * 1024;-const DEFAULT_TIMEOUT_MS = 10 * 60_000;+export const NPM_INSTALL_TIMEOUT_MS = 10 * 60_000;export const PROBE_TIMEOUT_MS = 30_000;export function enginesPrefix(baseDir = DATA_DIR): string {@@ -24,6 +24,25 @@ export function enginesBinDir(baseDir = DATA_DIR, platform: NodeJS.Platform = prreturn platform === "win32" ? enginesPrefix(baseDir) : join(enginesPrefix(baseDir), "bin");}+/** Where `npm install -g --prefix` puts packages: `lib/node_modules` on POSIX, `node_modules` on Windows. */+export function npmModulesIn(prefix: string, platform: NodeJS.Platform = process.platform): string {+ return platform === "win32" ? join(prefix, "node_modules") : join(prefix, "lib", "node_modules");+}++export function npmBinIn(prefix: string, platform: NodeJS.Platform = process.platform): string {+ return platform === "win32" ? prefix : join(prefix, "bin");+}++/** The version of `pkg` npm installed into the app's prefix, null when it has none there. */+export function npmCopyVersion(pkg: string, baseDir = DATA_DIR): string | null {+ try {+ const manifest = JSON.parse(readFileSync(join(npmModulesIn(enginesPrefix(baseDir)), ...pkg.split("/"), "package.json"), "utf8")) as { version?: unknown };+ return typeof manifest.version === "string" && manifest.version ? manifest.version : null;+ } catch {+ return null;+ }+}+/** Called once at boot: engines npm installed here win over any other copy on PATH. A standalone build the app installed* goes last instead, so a copy the person installs themselves takes over. */export function registerEnginesBinDir(baseDir = DATA_DIR, releases: readonly StandaloneRelease[] = STANDALONE_RELEASES): void {@@ -80,6 +99,8 @@ export function serverInstallFor(install: EngineInstall | undefined, npmPresent:interface InstallOptions {baseDir?: string;+ /** An exact version; npm's `latest` tag when omitted. */+ version?: string;cli?: string;timeoutMs?: number;env?: NodeJS.ProcessEnv;@@ -90,20 +111,27 @@ const running = new Map<string, Promise<void>>();/** Install or update one npm engine. Concurrent clicks share one npm run. */export function installNpmEngine(pkg: string, options: InstallOptions = {}): Promise<void> {- const key = `${options.baseDir ?? DATA_DIR} ${pkg}`;+ return oneNpmRunPer(pkg, options.baseDir, () => installOnce(pkg, options));+}++/** Installs and updates of one package in one prefix never overlap: a second caller joins the run in flight. */+export function oneNpmRunPer(pkg: string, baseDir: string | undefined, start: () => Promise<void>): Promise<void> {+ const key = `${baseDir ?? DATA_DIR} ${pkg}`;const existing = running.get(key);if (existing) return existing;- const run = installOnce(pkg, options).finally(() => running.delete(key));+ const run = start().finally(() => running.delete(key));running.set(key, run);return run;}-async function installOnce(pkg: string, options: InstallOptions): Promise<void> {- const prefix = enginesPrefix(options.baseDir);- mkdirSync(prefix, { recursive: true });+export function npmRunning(pkg: string, baseDir = DATA_DIR): boolean {+ return running.has(`${baseDir} ${pkg}`);+}++export function npmEnvironment(base: NodeJS.ProcessEnv = process.env, path: string = augmentedPath()): NodeJS.ProcessEnv {const env: NodeJS.ProcessEnv = {- ...(options.env ?? process.env),- PATH: options.path ?? augmentedPath(),+ ...base,+ PATH: path,NO_COLOR: "1",npm_config_update_notifier: "false",npm_config_fund: "false",@@ -111,10 +139,33 @@ async function installOnce(pkg: string, options: InstallOptions): Promise<void>};// Workspace credentials (xai/box/voice keys) are not npm's to see.stripWorkspaceCredentialEnv(env as Record<string, string | undefined>);- // npm 11 skips a dependency's install script unless the package is named here (Claude Code needs one), and Codex ships- // its native binary as a platform optional dependency, which a user-level `omit=optional` must not drop.- const args = ["install", "-g", "--prefix", prefix, "--loglevel=error", "--include=optional", `--allow-scripts=${pkg}`, `${pkg}@latest`];- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;+ return env;+}++/** npm 11 skips a dependency's install script unless the package is named here (Claude Code needs one), and Codex ships+ * its native binary as a platform optional dependency, which a user-level `omit=optional` must not drop. */+export function npmInstallArgs(prefix: string, pkg: string, version = "latest"): string[] {+ return ["install", "-g", "--prefix", prefix, "--loglevel=error", "--include=optional", `--allow-scripts=${pkg}`, `${pkg}@${version}`];+}++/** The version npm's `latest` tag names for `pkg` now. */+export async function npmLatestVersion(pkg: string, baseDir = DATA_DIR): Promise<string> {+ const prefix = enginesPrefix(baseDir);+ mkdirSync(prefix, { recursive: true });+ const result = await runNpm(["view", `${pkg}@latest`, "version", "--loglevel=error"], npmEnvironment(), prefix, PROBE_TIMEOUT_MS * 2);+ const version = stripVTControlCharacters(result.output).split(/\r?\n/).map((line) => line.trim()).filter(Boolean).at(-1);+ if (result.code !== 0 || !version || !/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(version)) {+ throw new Error(`npm could not look up the newest ${pkg}.${tail(result.output)}`);+ }+ return version;+}++async function installOnce(pkg: string, options: InstallOptions): Promise<void> {+ const prefix = enginesPrefix(options.baseDir);+ mkdirSync(prefix, { recursive: true });+ const env = npmEnvironment(options.env, options.path);+ const args = npmInstallArgs(prefix, pkg, options.version);+ const timeoutMs = options.timeoutMs ?? NPM_INSTALL_TIMEOUT_MS;await runInstall(pkg, args, env, prefix, timeoutMs);const binDir = enginesBinDir(options.baseDir);registerPathDir(binDir);@@ -152,14 +203,14 @@ function probeCli(cli: string, env: NodeJS.ProcessEnv): Promise<string | null> {});}-function tail(output: string): string {+export function tail(output: string): string {const clean = stripVTControlCharacters(output).trim();if (!clean) return "";const lines = clean.split(/\r?\n/).filter((line) => line.trim()).slice(-6);return `\n${lines.join("\n").slice(-600)}`;}-function runNpm(args: string[], env: NodeJS.ProcessEnv, cwd: string, timeoutMs: number): Promise<{ code: number | null; output: string }> {+export function runNpm(args: string[], env: NodeJS.ProcessEnv, cwd: string, timeoutMs: number): Promise<{ code: number | null; output: string }> {return new Promise((resolveRun, rejectRun) => {let child: ReturnType<typeof spawnCli>;try {diff --git a/server/engine-npm-update.ts b/server/engine-npm-update.tsnew file mode 100644index 0000000000..f6e6cf7ca6--- /dev/null+++ b/server/engine-npm-update.ts@@ -0,0 +1,234 @@+// Updating an npm engine in the app's prefix without ever leaving it half-installed. npm installs the new version into a+// staging prefix beside the real one; its command must start there and name the version; then the package folder takes+// the old one's place by rename (same filesystem) and its commands are moved next to it. npm writes those commands with+// paths relative to the prefix (POSIX links into ../lib/node_modules, Windows shims through %~dp0), so they work from+// either prefix. The old folder waits aside until the moved copy has started again, and comes back on any failure.+import { randomUUID } from "node:crypto";+import { existsSync, readdirSync, readFileSync } from "node:fs";+import { lstat, mkdir, readFile, readlink, rename, rm, symlink, unlink, writeFile } from "node:fs/promises";+import { basename, dirname, join } from "node:path";+import { stripVTControlCharacters } from "node:util";++import { DATA_DIR } from "./config.ts";+import {+ enginesPrefix, npmBinIn, npmEnvironment, npmInstallArgs, npmModulesIn, NPM_INSTALL_TIMEOUT_MS, oneNpmRunPer, PROBE_TIMEOUT_MS, runNpm, tail,+} from "./engine-install.ts";+import { replaceFile } from "./engine-standalone.ts";+import { resetPathCache } from "./env-path.ts";+import { execCli } from "./procs.ts";++const STAGING_PREFIX = ".npm-staging-";+const ASIDE_PREFIX = ".npm-aside-";+const ASIDE_RECORD = "aside.json";+const ASIDE_PACKAGE = "package";++export interface StagedNpmUpdate {+ pkg: string;+ version: string;+ baseDir?: string;+ /** The command to check; the package's first command when it is not one of them. */+ cli?: string;+ env?: NodeJS.ProcessEnv;+ timeoutMs?: number;+ /** Runs on the staged command once it has started, just before anything is replaced: a reason stops the update. */+ beforeSwitch?: (command: string) => Promise<string | null>;+ /** Tests only: the platform whose file locks apply, and the rename that meets them. */+ host?: { platform: NodeJS.Platform; rename: typeof rename };+}++/** The update was stopped before the switch because something still holds the engine; the old copy is untouched. */+export class EngineInUse extends Error {}++function toolsDir(baseDir: string): string {+ return dirname(enginesPrefix(baseDir));+}++function packageDir(prefix: string, pkg: string): string {+ return join(npmModulesIn(prefix), ...pkg.split("/"));+}++/** The commands a package declares, as npm names them. */+export function npmCommandNames(dir: string, pkg: string): string[] {+ try {+ const { bin } = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")) as { bin?: unknown };+ if (typeof bin === "string") return [basename(pkg)];+ return bin && typeof bin === "object" ? Object.keys(bin).filter((name) => /^[\w.-]+$/u.test(name)) : [];+ } catch {+ return [];+ }+}++/** What npm puts in its bin folder for one command: a link on POSIX, three shims on Windows. */+function commandEntries(name: string): string[] {+ return process.platform === "win32" ? [name, `${name}.cmd`, `${name}.ps1`] : [name];+}++function commandPath(prefix: string, name: string): string {+ return join(npmBinIn(prefix), process.platform === "win32" ? `${name}.cmd` : name);+}++/** Null when `<command> --version` exits cleanly and names `version`; otherwise what went wrong. */+export function versionFailure(command: string, version: string, env: NodeJS.ProcessEnv): Promise<string | null> {+ return new Promise((resolveProbe) => {+ execCli(command, ["--version"], { env, timeout: PROBE_TIMEOUT_MS, killSignal: "SIGKILL", maxBuffer: 64 * 1024 }, (error, stdout, stderr) => {+ const lines = stripVTControlCharacters(`${stdout}\n${stderr ?? ""}`).split(/\r?\n/u).map((line) => line.trim()).filter(Boolean);+ if (error) return resolveProbe((lines.find((line) => /^\w*Error: /u.test(line)) ?? lines[0] ?? error.message).slice(0, 400));+ if (!lines.some((line) => line.includes(version))) return resolveProbe(`it reported version ${(lines[0] ?? "nothing").slice(0, 80)}, not ${version}`);+ resolveProbe(null);+ });+ });+}++type SavedEntry = { path: string; link: string } | { path: string; data: Buffer } | { path: string; absent: true };++async function saveEntry(path: string): Promise<SavedEntry> {+ const info = await lstat(path).catch(() => null);+ if (!info) return { path, absent: true };+ return info.isSymbolicLink() ? { path, link: await readlink(path) } : { path, data: await readFile(path) };+}++async function restoreEntry(entry: SavedEntry): Promise<void> {+ await rm(entry.path, { force: true });+ if ("link" in entry) await symlink(entry.link, entry.path);+ else if ("data" in entry) await writeFile(entry.path, entry.data, { mode: 0o755 });+}++function lockedError(error: unknown): boolean {+ const code = (error as NodeJS.ErrnoException).code;+ return code === "EPERM" || code === "EACCES" || code === "EBUSY";+}++/** Moves the staged package and its commands into the live prefix, keeping the old ones aside until the moved command+ * starts; on Windows a folder holding a running program cannot be renamed, which stops the switch before it begins. */+async function switchIn(staging: string, pkg: string, version: string, command: string, env: NodeJS.ProcessEnv, baseDir: string, fs: { platform: NodeJS.Platform; rename: typeof rename }): Promise<void> {+ const prefix = enginesPrefix(baseDir);+ const live = packageDir(prefix, pkg);+ const aside = join(toolsDir(baseDir), `${ASIDE_PREFIX}${randomUUID()}`);+ const kept = join(aside, ASIDE_PACKAGE);+ await mkdir(dirname(live), { recursive: true });+ await mkdir(aside, { mode: 0o700 });+ await writeFile(join(aside, ASIDE_RECORD), `${JSON.stringify({ pkg })}\n`);+ const hadLive = existsSync(live);+ if (hadLive) {+ try {+ await fs.rename(live, kept);+ } catch (error) {+ await rm(aside, { recursive: true, force: true }).catch(() => {});+ if (fs.platform === "win32" && lockedError(error)) throw new EngineInUse(`${pkg} is still running`);+ throw error;+ }+ }+ const putBack = async () => {+ await rm(live, { recursive: true, force: true });+ if (hadLive) await fs.rename(kept, live);+ };+ try {+ await fs.rename(packageDir(staging, pkg), live);+ } catch (error) {+ if (!hadLive || await fs.rename(kept, live).then(() => true, () => false)) await rm(aside, { recursive: true, force: true }).catch(() => {});+ throw error;+ }+ const saved: SavedEntry[] = [];+ try {+ await mkdir(npmBinIn(prefix), { recursive: true });+ for (const name of npmCommandNames(live, pkg)) {+ for (const entry of commandEntries(name)) {+ const from = join(npmBinIn(staging), entry);+ if (!(await lstat(from).catch(() => null))) continue;+ const to = join(npmBinIn(prefix), entry);+ saved.push(await saveEntry(to));+ await replaceFile(from, to);+ }+ }+ const failure = await versionFailure(commandPath(prefix, command), version, env);+ if (failure) throw new Error(`${pkg} ${version} did not start once in place: ${failure}`);+ } catch (error) {+ for (const entry of saved.reverse()) await restoreEntry(entry).catch(() => {});+ // Should putting it back fail, the old copy stays aside for the next sweep to restore.+ if (await putBack().then(() => true, () => false)) await rm(aside, { recursive: true, force: true }).catch(() => {});+ throw error;+ }+ // A file Windows still holds goes at the next sweep.+ await rm(aside, { recursive: true, force: true }).catch(() => {});+}++/** Installs `pkg@version` beside the live copy, checks it, then switches. Any failure leaves the live copy as it was. */+export function updateNpmEngineStaged(options: StagedNpmUpdate): Promise<void> {+ const baseDir = options.baseDir ?? DATA_DIR;+ return oneNpmRunPer(options.pkg, baseDir, () => stagedOnce(options, baseDir));+}++async function stagedOnce(options: StagedNpmUpdate, baseDir: string): Promise<void> {+ const { pkg, version } = options;+ const env = npmEnvironment(options.env);+ const staging = join(toolsDir(baseDir), `${STAGING_PREFIX}${randomUUID()}`);+ try {+ await mkdir(staging, { recursive: true, mode: 0o700 });+ const result = await runNpm(npmInstallArgs(staging, pkg, version), env, staging, options.timeoutMs ?? NPM_INSTALL_TIMEOUT_MS);+ if (result.code !== 0) throw new Error(`npm could not install ${pkg} ${version}.${tail(result.output)}`);+ const names = npmCommandNames(packageDir(staging, pkg), pkg);+ const command = options.cli && names.includes(options.cli) ? options.cli : names[0];+ if (!command) throw new Error(`${pkg} ${version} has no command to run.`);+ const failure = await versionFailure(commandPath(staging, command), version, env)+ ?? await options.beforeSwitch?.(commandPath(staging, command)) ?? null;+ if (failure) throw new Error(`${pkg} ${version} does not start: ${failure}`);+ await switchIn(staging, pkg, version, command, env, baseDir, options.host ?? { platform: process.platform, rename });+ } finally {+ await rm(staging, { recursive: true, force: true, maxRetries: 4, retryDelay: 250 }).catch(() => {});+ }+}++/** Removes an npm copy the app no longer uses: its commands that lead into it, then its folder. */+export async function removeNpmCopy(pkg: string, baseDir = DATA_DIR): Promise<void> {+ const prefix = enginesPrefix(baseDir);+ const live = packageDir(prefix, pkg);+ if (!existsSync(live)) return;+ const names = npmCommandNames(live, pkg);+ const aside = join(toolsDir(baseDir), `${ASIDE_PREFIX}${randomUUID()}`);+ await mkdir(aside, { mode: 0o700 });+ try {+ await rename(live, join(aside, ASIDE_PACKAGE));+ } catch (error) {+ await rm(aside, { recursive: true, force: true }).catch(() => {});+ if (process.platform === "win32" && lockedError(error)) throw new EngineInUse(`${pkg} is still running`);+ throw error;+ }+ const separator = process.platform === "win32" ? "\\" : "/";+ const marker = ["node_modules", ...pkg.split("/"), ""].join(separator);+ for (const name of names) {+ for (const entry of commandEntries(name)) {+ const path = join(npmBinIn(prefix), entry);+ const saved = await saveEntry(path).catch(() => null);+ const target = saved && "link" in saved ? saved.link : saved && "data" in saved ? saved.data.toString("utf8") : "";+ if (target.includes(marker)) await unlink(path).catch(() => {});+ }+ }+ resetPathCache();+ await rm(aside, { recursive: true, force: true }).catch(() => {});+}++/** An interrupted switch leaves the old folder aside with nothing in its place: it goes back. Staging folders and+ * anything else aside are removed. */+export async function sweepNpmLeftovers(baseDir = DATA_DIR): Promise<void> {+ const tools = toolsDir(baseDir);+ let names: string[];+ try {+ names = readdirSync(tools);+ } catch {+ return;+ }+ for (const name of names) {+ const path = join(tools, name);+ if (name.startsWith(ASIDE_PREFIX)) {+ try {+ const { pkg } = JSON.parse(readFileSync(join(path, ASIDE_RECORD), "utf8")) as { pkg?: unknown };+ const live = typeof pkg === "string" ? packageDir(enginesPrefix(baseDir), pkg) : null;+ if (live && !existsSync(live) && existsSync(join(path, ASIDE_PACKAGE))) {+ await mkdir(dirname(live), { recursive: true });+ await rename(join(path, ASIDE_PACKAGE), live);+ }+ } catch {}+ } else if (!name.startsWith(STAGING_PREFIX)) continue;+ await rm(path, { recursive: true, force: true }).catch(() => {});+ }+}diff --git a/server/engine-standalone.ts b/server/engine-standalone.tsindex dc276c8de0..1f938b59e7 100644--- a/server/engine-standalone.ts+++ b/server/engine-standalone.ts@@ -71,6 +71,8 @@ export interface StandaloneInstallOptions {timeoutMs?: number;/** How long the download may go without a single byte. */stallMs?: number;+ /** Runs on the new program once it has started, just before it replaces anything: a reason stops the install. */+ beforeSwitch?: (program: string) => Promise<string | null>;}interface InstallRecord {@@ -323,6 +325,12 @@ export function registerStandaloneBinDirs(baseDir = DATA_DIR, releases: readonly}}+/** The version the app's copy of this engine points at, checked or not; null when the app installed none. */+export function standaloneCurrentVersion(release: StandaloneRelease, baseDir = DATA_DIR): string | null {+ const pointer = readJsonFile(join(standaloneEngineDir(release.engine, baseDir), CURRENT)) as Partial<CurrentPointer> | null;+ return typeof pointer?.version === "string" && usableVersionName(pointer.version) ? pointer.version : null;+}+function resolvesInside(folder: string, cli: string, path?: string): boolean {const resolved = findCliCandidates(cli, path)[0];return resolved !== undefined && inside(realOrResolved(folder), realOrResolved(resolved));@@ -578,7 +586,7 @@ function lockedError(error: unknown): boolean {}/** Moves `from` onto `to`. Windows will not replace a program that is running but lets it be renamed, so it steps aside. */-async function replaceFile(from: string, to: string): Promise<void> {+export async function replaceFile(from: string, to: string): Promise<void> {try {await rename(from, to);return;@@ -745,7 +753,7 @@ async function installOnce(release: StandaloneRelease, options: StandaloneInstalif (signedHere(key, release) && !(await macSignerOk(stagedProgram, release, codesign))) {throw Object.assign(new StandaloneInstallError(`The downloaded ${release.name} is not signed by its maker, so nothing was installed.`), userErrorFields(userError("serverError.install.notSigned", { name: release.name })));}- const failure = await probeVersion(stagedProgram, release);+ const failure = await probeVersion(stagedProgram, release) ?? await options.beforeSwitch?.(stagedProgram) ?? null;if (failure !== null) {throw Object.assign(new StandaloneInstallError(`${release.name} was downloaded, but it doesn't start on this computer (${failure}). Nothing was installed.`), userErrorFields(userError("serverError.install.downloadDoesNotStart", { name: release.name, failure: failure })));}diff --git a/server/engine-updates-host.ts b/server/engine-updates-host.tsnew file mode 100644index 0000000000..aa1f891ec5--- /dev/null+++ b/server/engine-updates-host.ts@@ -0,0 +1,35 @@+import { join } from "node:path";++import { DATA_DIR } from "./config.ts";+import type { AnyProviderDriver } from "./contracts.ts";+import { validateAntigravityRuntime } from "./drivers/antigravity-acp.ts";+import { antigravityManagedInstallAvailable, antigravityOlderRuntime, installAntigravityRuntime } from "./drivers/antigravity-runtime.ts";+import { antigravityRuntimesRoot } from "./engine-roots.ts";+import { createEngineUpdater, enginePlans, type EngineUpdater, type ManagedRuntime } from "./engine-updates.ts";++function managedRuntimes(): Record<string, ManagedRuntime> {+ if (!antigravityManagedInstallAvailable()) return {};+ return {+ antigravityAgent: {+ older: () => antigravityOlderRuntime(),+ install: () => installAntigravityRuntime({ validate: validateAntigravityRuntime }).then(() => {}),+ folder: antigravityRuntimesRoot(DATA_DIR),+ },+ };+}++/** The server's engine updater; `start()` it once the server is up. */+export function engineUpdatesFor(deps: {+ drivers: readonly AnyProviderDriver[];+ turnRunning(): boolean;+ configuredClis(): readonly string[];+ updated(): void;+}): EngineUpdater {+ return createEngineUpdater({+ plans: enginePlans(deps.drivers, managedRuntimes()),+ statePath: join(DATA_DIR, "providers", "engine-updates.json"),+ turnRunning: deps.turnRunning,+ configuredClis: deps.configuredClis,+ updated: deps.updated,+ });+}diff --git a/server/engine-updates.test.ts b/server/engine-updates.test.tsnew file mode 100644index 0000000000..4c01e785a2--- /dev/null+++ b/server/engine-updates.test.ts@@ -0,0 +1,370 @@+import { createHash } from "node:crypto";+import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";+import { rename } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { StandaloneRelease } from "./contracts.ts";+import { BUILT_IN_DRIVERS } from "./drivers/builtIn.ts";+import { enginesBinDir, enginesPrefix, installNpmEngine, npmCopyVersion, npmModulesIn, npmPackageOf } from "./engine-install.ts";+import { acpHandshake } from "./engine-handshake.ts";+import { EngineInUse, updateNpmEngineStaged } from "./engine-npm-update.ts";+import { installStandaloneEngine, resetStandaloneStateForTests, standaloneCurrentVersion, standalonePlatformKey } from "./engine-standalone.ts";+import { createEngineUpdater, ENGINE_UPDATE_BUSY_RETRY_MS, ENGINE_UPDATE_EVERY_MS, ENGINE_UPDATE_START_DELAY_MS, enginePlans, type EnginePlan, type EngineUpdaterOptions } from "./engine-updates.ts";+import { ENGINE_VERSIONS, LATEST } from "./engine-versions.ts";+import { resetPathCacheForTests } from "./env-path.ts";+import { removeTempDir } from "./testing/cleanup.ts";+import { isNewerVersion } from "./update-check.ts";++// A stand-in npm that lays a global install out as npm does (lib/node_modules/<pkg> and a relative link in bin/). The+// command prints its version; FAKE_NPM_MODE makes the next install's command fail everywhere ("broken") or only once+// moved out of the prefix npm installed it into ("pinned"), as a package that wrote its install path down would.+const FAKE_NPM = `#!/usr/bin/env node+const { appendFileSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } = require('node:fs');+const { join } = require('node:path');+const args = process.argv.slice(2);+appendFileSync(process.env.FAKE_NPM_LOG, JSON.stringify(args) + '\\n');+if (args[0] === 'view') { console.log(process.env.FAKE_NPM_LATEST); process.exit(0); }+const mode = process.env.FAKE_NPM_MODE || 'ok';+const prefix = realpathSync(args[args.indexOf('--prefix') + 1]);+const spec = args[args.length - 1];+const pkg = spec.slice(0, spec.lastIndexOf('@'));+const version = spec.slice(spec.lastIndexOf('@') + 1);+const dir = join(prefix, 'lib', 'node_modules', ...pkg.split('/'));+rmSync(dir, { recursive: true, force: true });+mkdirSync(dir, { recursive: true });+writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: pkg, version, bin: { fakebin: 'cli.js' } }));+const body = mode === 'broken' ? 'console.error("Error: Missing optional dependency"); process.exit(1);'+ : mode === 'pinned' ? 'if (!__dirname.startsWith(' + JSON.stringify(prefix) + ')) { console.error("Error: Cannot find module"); process.exit(1); } console.log(' + JSON.stringify(version) + ');'+ : 'console.log(' + JSON.stringify(version) + ');';+writeFileSync(join(dir, 'cli.js'), '#!/usr/bin/env node\\n' + body + '\\n', { mode: 0o755 });+mkdirSync(join(prefix, 'bin'), { recursive: true });+rmSync(join(prefix, 'bin', 'fakebin'), { force: true });+symlinkSync(join('..', 'lib', 'node_modules', ...pkg.split('/'), 'cli.js'), join(prefix, 'bin', 'fakebin'));+`;++const sha256 = (data: string | Buffer) => createHash("sha256").update(data).digest("hex");++function noSteps(): EngineUpdaterOptions["steps"] {+ return {+ sweep: async () => {},+ npmVersion: () => null,+ standaloneVersion: () => null,+ };+}++describe("the version table", () => {+ it("pins every engine the app installs, at or above its minimum, and a standalone engine at its pinned build", () => {+ for (const driver of BUILT_IN_DRIVERS) {+ const installs = Boolean(npmPackageOf(driver.install) || driver.install?.standalone || driver.install?.managed);+ expect(Boolean(ENGINE_VERSIONS[driver.driverKind]), driver.driverKind).toBe(installs);+ }+ for (const [kind, pin] of Object.entries(ENGINE_VERSIONS)) {+ if (pin.target !== LATEST) expect(isNewerVersion(pin.minimum, pin.target), kind).toBe(false);+ }+ for (const plan of enginePlans(BUILT_IN_DRIVERS)) {+ if (plan.standalone) expect(plan.pin.target).toBe(plan.standalone.version);+ }+ });+});++describe("waking from a sleep", () => {+ afterEach(() => vi.useRealTimers());++ it("checks once the wall clock passes the next check, though the suspended timers did not", async () => {+ vi.useFakeTimers();+ const start = Date.UTC(2026, 10, 7, 9);+ vi.setSystemTime(start);+ const scratch = mkdtempSync(join(tmpdir(), "omb-engine-updates-"));+ let passes = 0;+ const updater = createEngineUpdater({+ plans: [], baseDir: scratch, statePath: join(scratch, "state.json"), turnRunning: () => false,+ steps: { ...noSteps(), sweep: async () => { passes += 1; } },+ });+ const timer = updater.start();+ try {+ await vi.advanceTimersByTimeAsync(ENGINE_UPDATE_START_DELAY_MS + 60_000);+ expect(passes).toBe(1);+ expect(updater.dueAt()).toBeGreaterThan(Date.now() + ENGINE_UPDATE_EVERY_MS - 2 * 60_000);+ // A suspended machine: the wall clock moves on a day and more while no timer runs.+ vi.setSystemTime(Date.now() + ENGINE_UPDATE_EVERY_MS + 60 * 60_000);+ expect(passes).toBe(1);+ await vi.advanceTimersByTimeAsync(61_000);+ expect(passes).toBe(2);+ await vi.advanceTimersByTimeAsync(60 * 60_000);+ expect(passes).toBe(2);+ } finally {+ timer.stop();+ vi.useRealTimers();+ await removeTempDir(scratch);+ }+ });+});++describe.skipIf(process.platform === "win32")("updating the app's engine copies", () => {+ let scratch = "";+ let base = "";+ let originalPath: string | undefined;+ const lines: string[] = [];+ let turn = false;+ let live: string[][] = [];++ beforeEach(() => {+ scratch = mkdtempSync(join(tmpdir(), "omb-engine-updates-"));+ base = join(scratch, "data");+ const fakePath = join(scratch, "fake-path");+ mkdirSync(fakePath);+ writeFileSync(join(fakePath, "npm"), FAKE_NPM, { mode: 0o755 });+ chmodSync(join(fakePath, "npm"), 0o755);+ symlinkSync(process.execPath, join(fakePath, "node"));+ originalPath = process.env.PATH;+ process.env.PATH = `${fakePath}:/usr/bin:/bin`;+ process.env.FAKE_NPM_LOG = join(scratch, "npm.jsonl");+ writeFileSync(process.env.FAKE_NPM_LOG, "");+ delete process.env.FAKE_NPM_MODE;+ resetPathCacheForTests();+ resetStandaloneStateForTests();+ lines.length = 0;+ turn = false;+ live = [];+ });+ afterEach(async () => {+ process.env.PATH = originalPath;+ delete process.env.FAKE_NPM_LOG;+ delete process.env.FAKE_NPM_MODE;+ delete process.env.FAKE_NPM_LATEST;+ resetPathCacheForTests();+ resetStandaloneStateForTests();+ await removeTempDir(scratch);+ });++ const npmRuns = () => readFileSync(process.env.FAKE_NPM_LOG!, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line) as string[]);+ const installs = () => npmRuns().filter((args) => args[0] === "install");+ const plan = (pin: Partial<EnginePlan["pin"]> = {}, extra: Partial<EnginePlan> = {}): EnginePlan => ({+ driverKind: "fakeEngine", name: "Fake Engine", cli: "fakebin", npm: "fake-engine",+ pin: { target: "2.2.5", minimum: "1.19.4", ...pin }, ...extra,+ });+ const updater = (plans: EnginePlan[], extra: Partial<EngineUpdaterOptions> = {}) => createEngineUpdater({+ plans, baseDir: base, statePath: join(base, "providers", "engine-updates.json"),+ turnRunning: () => turn, liveCommands: () => live, log: (line) => lines.push(line),+ switchWait: { forMs: 0, everyMs: 1 }, ...extra,+ });+ const runsFakebin = () => readFileSync(join(npmModulesIn(enginesPrefix(base)), "fake-engine", "cli.js"), "utf8");+ const leftovers = () => readdirSync(join(base, "tools")).filter((name) => name.startsWith("."));++ it("moves an old copy up to the target beside it, and says so once on the engine's row", async () => {+ await installNpmEngine("fake-engine", { baseDir: base, cli: "fakebin", version: "1.19.4" });+ const updated = vi.fn();+ const engines = updater([plan()], { updated });+ await engines.check();++ expect(npmCopyVersion("fake-engine", base)).toBe("2.2.5");+ expect(runsFakebin()).toContain('"2.2.5"');+ expect(lstatSync(join(enginesBinDir(base), "fakebin")).isSymbolicLink()).toBe(true);+ expect(installs().at(-1)).toContain("[email protected]");+ expect(installs().at(-1)![installs().at(-1)!.indexOf("--prefix") + 1]).not.toBe(enginesPrefix(base));+ expect(leftovers()).toEqual([]);+ expect(lines).toEqual(["Engine update: Fake Engine 1.19.4 → 2.2.5"]);+ expect(updated).toHaveBeenCalledTimes(1);+ expect(engines.shown("fakeEngine")).toEqual({ autoUpdated: { version: "2.2.5", at: expect.any(Number) } });+ expect(engines.shown("other")).toEqual({});+ });++ it("does nothing to a copy already at its target, nor to an engine the app did not install", async () => {+ await installNpmEngine("fake-engine", { baseDir: base, cli: "fakebin", version: "2.2.5" });+ const before = installs().length;+ const updated = vi.fn();+ await updater([plan(), plan({}, { driverKind: "absent", npm: "not-installed" })], { updated }).check();+ expect(installs()).toHaveLength(before);+ expect(npmCopyVersion("not-installed", base)).toBeNull();+ expect(lines).toEqual([]);+ expect(updated).not.toHaveBeenCalled();+ });++ it("follows npm's newest for an engine that tracks it, and only when it is newer", async () => {+ await installNpmEngine("fake-engine", { baseDir: base, cli: "fakebin", version: "2.1.300" });+ process.env.FAKE_NPM_LATEST = "2.1.300";+ await updater([plan({ target: LATEST, minimum: "2.1.267" })]).check();+ expect(installs()).toHaveLength(1);+ process.env.FAKE_NPM_LATEST = "2.1.319";+ await updater([plan({ target: LATEST, minimum: "2.1.267" })]).check();+ expect(npmCopyVersion("fake-engine", base)).toBe("2.1.319");+ });++ it("waits while a turn runs or the engine's process is up, then updates once idle", async () => {+ await installNpmEngine("fake-engine", { baseDir: base, cli: "fakebin", version: "1.19.4" });+ const engines = updater([plan()]);+ turn = true;+ await engines.check();+ expect(npmCopyVersion("fake-engine", base)).toBe("1.19.4");+ expect(installs()).toHaveLength(1);+ expect(engines.dueAt()).toBeLessThanOrEqual(Date.now() + ENGINE_UPDATE_BUSY_RETRY_MS);++ turn = false;+ live = [["/usr/bin/env", "node", join(enginesBinDir(base), "fakebin"), "acp"]];+ await engines.check();+ expect(npmCopyVersion("fake-engine", base)).toBe("1.19.4");++ live = [];+ await engines.check();+ expect(npmCopyVersion("fake-engine", base)).toBe("2.2.5");+ expect(lines).toEqual(["Engine update: Fake Engine 1.19.4 → 2.2.5"]);+ });++ it("keeps the old copy when the new one does not start, and tries again later", async () => {+ await installNpmEngine("fake-engine", { baseDir: base, cli: "fakebin", version: "1.19.4" });+ process.env.FAKE_NPM_MODE = "broken";+ const engines = updater([plan()]);+ await engines.check();+ expect(npmCopyVersion("fake-engine", base)).toBe("1.19.4");+ expect(runsFakebin()).toContain('"1.19.4"');+ expect(leftovers()).toEqual([]);+ expect(lines).toHaveLength(1);+ expect(lines[0]).toMatch(/^Engine update: Fake Engine stays on 1\.19\.4; 2\.2\.5 could not be installed \(.*Missing optional dependency.*\)\. Trying again later\.$/);+ expect(engines.dueAt()).toBeGreaterThan(Date.now() + 30 * 60_000);+ expect(engines.dueAt()).toBeLessThanOrEqual(Date.now() + 60 * 60_000);++ delete process.env.FAKE_NPM_MODE;+ await engines.check();+ expect(installs()).toHaveLength(2);+ });++ it("puts the old copy back when the new one stops starting once moved into place", async () => {+ await installNpmEngine("fake-engine", { baseDir: base, cli: "fakebin", version: "1.19.4" });+ process.env.FAKE_NPM_MODE = "pinned";+ await updater([plan()]).check();+ expect(npmCopyVersion("fake-engine", base)).toBe("1.19.4");+ expect(runsFakebin()).toContain('"1.19.4"');+ expect(leftovers()).toEqual([]);+ expect(lines[0]).toContain("did not start once in place");+ });++ it("does not switch to a copy that refuses the engine's handshake", async () => {+ await installNpmEngine("fake-engine", { baseDir: base, cli: "fakebin", version: "1.19.4" });+ const handshake = vi.fn(async () => "it refused the ACP handshake");+ await updater([plan({ acp: ["acp"] })], { steps: { handshake } }).check();+ expect(handshake).toHaveBeenCalledWith(expect.stringContaining(".npm-staging-"), ["acp"], expect.any(Object));+ expect(npmCopyVersion("fake-engine", base)).toBe("1.19.4");+ expect(lines[0]).toContain("it refused the ACP handshake");+ });++ it("leaves a copy Windows holds open where it is and tries again without counting a failure", async () => {+ await installNpmEngine("fake-engine", { baseDir: base, cli: "fakebin", version: "1.19.4" });+ const livePackage = join(npmModulesIn(enginesPrefix(base)), "fake-engine");+ const lockedRename = (async (from, to) => {+ if (String(from) === livePackage) throw Object.assign(new Error("EPERM: operation not permitted, rename"), { code: "EPERM", syscall: "rename" });+ return rename(from, to);+ }) as typeof rename;+ await expect(updateNpmEngineStaged({ pkg: "fake-engine", version: "2.2.5", baseDir: base, cli: "fakebin", host: { platform: "win32", rename: lockedRename } }))+ .rejects.toBeInstanceOf(EngineInUse);+ expect(npmCopyVersion("fake-engine", base)).toBe("1.19.4");+ expect(leftovers()).toEqual([]);++ const engines = updater([plan()], { steps: { updateNpm: (options) => updateNpmEngineStaged({ ...options, host: { platform: "win32", rename: lockedRename } }) } });+ await engines.check();+ expect(lines).toEqual([]);+ expect(engines.dueAt()).toBeLessThanOrEqual(Date.now() + ENGINE_UPDATE_BUSY_RETRY_MS);+ await updater([plan()]).check();+ expect(npmCopyVersion("fake-engine", base)).toBe("2.2.5");+ });++ it("moves an old npm copy to the app's own build, removing the npm copy only once the build is in place", async () => {+ await installNpmEngine("fake-old", { baseDir: base, cli: "fakebin", version: "1.19.4" });+ const program = "#!/bin/sh\necho 'fake 2.2.5'\n";+ const release: StandaloneRelease = {+ name: "Fake Engine", engine: "fake-engine", version: "2.2.5", hosts: ["downloads.example.test"],+ assets: { [standalonePlatformKey()]: { url: "https://downloads.example.test/fake", archive: "raw", executable: "fakebin", approxBytes: program.length, sha256: sha256(program), executableSha256: sha256(program) } },+ };+ const fetchImpl = (async () => new Response(program)) as unknown as typeof fetch;+ const migrate = plan({ formerNpm: ["fake-old"] }, { npm: undefined, standalone: release });++ let fail = true;+ const installStandalone = (r: StandaloneRelease, options: Parameters<typeof installStandaloneEngine>[1]) =>+ installStandaloneEngine(r, { ...options, fetchImpl: fail ? (async () => new Response("not it")) as unknown as typeof fetch : fetchImpl });+ const engines = updater([migrate], { steps: { installStandalone } });+ await engines.check();+ expect(standaloneCurrentVersion(release, base)).toBeNull();+ expect(npmCopyVersion("fake-old", base)).toBe("1.19.4");+ expect(lines[0]).toContain("Fake Engine stays on 1.19.4");++ fail = false;+ await updater([migrate], { steps: { installStandalone }, statePath: join(base, "after-the-backoff.json") }).check();+ expect(standaloneCurrentVersion(release, base)).toBe("2.2.5");+ expect(npmCopyVersion("fake-old", base)).toBeNull();+ expect(existsSync(join(enginesBinDir(base), "fakebin"))).toBe(false);+ expect(lines.at(-1)).toBe("Engine update: Fake Engine 1.19.4 → 2.2.5");+ });++ it("installs no build of the app's own that refuses the engine's handshake", async () => {+ await installNpmEngine("fake-old", { baseDir: base, cli: "fakebin", version: "1.19.4" });+ const program = "#!/bin/sh\necho 'fake 2.2.5'\n";+ const release: StandaloneRelease = {+ name: "Fake Engine", engine: "fake-engine", version: "2.2.5", hosts: ["downloads.example.test"],+ assets: { [standalonePlatformKey()]: { url: "https://downloads.example.test/fake", archive: "raw", executable: "fakebin", approxBytes: program.length, sha256: sha256(program), executableSha256: sha256(program) } },+ };+ const installStandalone = (r: StandaloneRelease, options: Parameters<typeof installStandaloneEngine>[1]) =>+ installStandaloneEngine(r, { ...options, fetchImpl: (async () => new Response(program)) as unknown as typeof fetch });+ await updater([plan({ formerNpm: ["fake-old"], acp: ["acp"] }, { npm: undefined, standalone: release })], {+ steps: { installStandalone, handshake: async () => "it refused the ACP handshake" },+ }).check();+ expect(standaloneCurrentVersion(release, base)).toBeNull();+ expect(npmCopyVersion("fake-old", base)).toBe("1.19.4");+ expect(lines[0]).toContain("it refused the ACP handshake");+ });++ it("keeps an npm copy a saved CLI path still runs", async () => {+ await installNpmEngine("fake-old", { baseDir: base, cli: "fakebin", version: "1.19.4" });+ const release: StandaloneRelease = { name: "Fake Engine", engine: "fake-engine", version: "2.2.5", hosts: [], assets: {} };+ await updater([plan({ formerNpm: ["fake-old"] }, { npm: undefined, standalone: release })], {+ configuredClis: () => [join(enginesBinDir(base), "fakebin")],+ steps: { standaloneVersion: () => "2.2.5" },+ }).check();+ expect(npmCopyVersion("fake-old", base)).toBe("1.19.4");+ });+});++describe("a runtime the app manages itself", () => {+ it("installs the pinned runtime beside an older one, and leaves one it never installed alone", async () => {+ const scratch = mkdtempSync(join(tmpdir(), "omb-engine-updates-"));+ try {+ const install = vi.fn(async () => {});+ const lines: string[] = [];+ let older: string | null = "1.4.2";+ const managed = { older: async () => older, install, folder: join(scratch, "runtimes") };+ const engines = createEngineUpdater({+ plans: [{ driverKind: "managedEngine", name: "Managed", pin: { target: "1.4.3", minimum: "1.4.3" }, managed }],+ baseDir: scratch, statePath: join(scratch, "state.json"), turnRunning: () => false, log: (line) => lines.push(line),+ liveCommands: () => [], steps: noSteps(),+ });+ await engines.check();+ expect(install).toHaveBeenCalledTimes(1);+ expect(lines).toEqual(["Engine update: Managed 1.4.2 → 1.4.3"]);+ older = null;+ await engines.check();+ expect(install).toHaveBeenCalledTimes(1);+ } finally {+ await removeTempDir(scratch);+ }+ });+});++describe.skipIf(process.platform === "win32")("the ACP handshake", () => {+ let scratch = "";+ beforeEach(() => { scratch = mkdtempSync(join(tmpdir(), "omb-handshake-")); });+ afterEach(async () => { await removeTempDir(scratch); });+ const agent = (body: string) => {+ const path = join(scratch, `agent-${Math.random().toString(36).slice(2)}`);+ writeFileSync(path, `#!${process.execPath}\n${body}\n`, { mode: 0o755 });+ return path;+ };++ it("passes a program that answers initialize, and says why one that does not fails", async () => {+ const answers = agent(`process.stdin.on("data", (chunk) => { const { id } = JSON.parse(String(chunk)); process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result: { protocolVersion: 1 } }) + "\\n"); });`);+ expect(await acpHandshake(answers, ["acp"], process.env)).toBeNull();+ const exits = agent(`console.error("unknown command: acp"); process.exit(2);`);+ expect(await acpHandshake(exits, ["acp"], process.env)).toBe("unknown command: acp");+ const silent = agent("setInterval(() => {}, 1000);");+ expect(await acpHandshake(silent, ["acp"], process.env, 300)).toBe("it did not answer the ACP handshake in time");+ });+});diff --git a/server/engine-updates.ts b/server/engine-updates.tsnew file mode 100644index 0000000000..a93abb826a--- /dev/null+++ b/server/engine-updates.ts@@ -0,0 +1,366 @@+// Keeps the engine copies the app installed itself at the versions this release was tested with (engine-versions.ts),+// with no button and no setting. An engine the app did not install is never touched, nor is a copy newer than its+// target. Updates wait until no turn runs and no process runs the engine, then install beside the old copy and switch+// only once the new one has started; a failure keeps the old copy and is tried again later.+import { mkdirSync, readFileSync } from "node:fs";+import { dirname, join, resolve, sep } from "node:path";++import { writeFileAtomic } from "./atomic.ts";+import { cliProbeEnvironment } from "./cli-probe.ts";+import { DATA_DIR, stripControlPlaneEnv } from "./config.ts";+import type { AnyProviderDriver, StandaloneRelease } from "./contracts.ts";+import { startDueTimer, type DueTimer } from "./due-timer.ts";+import { acpHandshake } from "./engine-handshake.ts";+import { enginesBinDir, enginesPrefix, npmCopyVersion, npmLatestVersion, npmModulesIn, npmPackageOf, npmRunning } from "./engine-install.ts";+import { EngineInUse, npmCommandNames, removeNpmCopy, sweepNpmLeftovers, updateNpmEngineStaged, type StagedNpmUpdate } from "./engine-npm-update.ts";+import { installStandaloneEngine, standaloneAssetFor, standaloneCurrentVersion, standaloneEngineDir, type StandaloneInstallOptions } from "./engine-standalone.ts";+import { ENGINE_VERSIONS, LATEST, type EngineVersionPin } from "./engine-versions.ts";+import { liveCliCommands } from "./procs.ts";+import { isNewerVersion } from "./update-check.ts";++export const ENGINE_UPDATE_START_DELAY_MS = 2 * 60_000;+export const ENGINE_UPDATE_EVERY_MS = 24 * 60 * 60_000;+export const ENGINE_UPDATE_BUSY_RETRY_MS = 5 * 60_000;+const FIRST_RETRY_MS = 60 * 60_000;+const BELOW_MINIMUM_RETRY_CAP_MS = 6 * 60 * 60_000;+/** How long "Updated to" stays on the engine's row. */+const SHOW_UPDATED_MS = 7 * 24 * 60 * 60_000;+/** Once a new copy is ready, how long the switch waits for the engine to be free before trying another day. */+const SWITCH_WAIT_MS = 10 * 60_000;+const SWITCH_POLL_MS = 15_000;++/** A runtime the app manages itself (Antigravity): it installs each version beside the others and checks it. */+export interface ManagedRuntime {+ /** The older version installed when the pinned one is not, else null. */+ older(): Promise<string | null>;+ install(): Promise<void>;+ folder: string;+}++export interface EnginePlan {+ driverKind: string;+ name: string;+ pin: EngineVersionPin;+ cli?: string;+ npm?: string;+ /** Only when it has a build for this computer. */+ standalone?: StandaloneRelease;+ managed?: ManagedRuntime;+}++export function enginePlans(drivers: readonly AnyProviderDriver[], managed: Readonly<Record<string, ManagedRuntime>> = {}): EnginePlan[] {+ return drivers.flatMap((driver) => {+ const pin = ENGINE_VERSIONS[driver.driverKind];+ if (!pin || !driver.install) return [];+ let cli: string | undefined;+ try {+ const value = (driver.defaultConfig() as { cli?: unknown })?.cli;+ cli = typeof value === "string" && value ? value : undefined;+ } catch {}+ const standalone = driver.install.standalone && standaloneAssetFor(driver.install.standalone) ? driver.install.standalone : undefined;+ return [{+ driverKind: driver.driverKind, name: driver.metadata.displayName, pin, cli,+ npm: npmPackageOf(driver.install) ?? undefined, standalone, managed: managed[driver.driverKind],+ }];+ });+}++export interface UpdateSteps {+ npmVersion(pkg: string, baseDir: string): string | null;+ npmLatest(pkg: string, baseDir: string): Promise<string>;+ updateNpm(options: StagedNpmUpdate): Promise<void>;+ removeNpm(pkg: string, baseDir: string): Promise<void>;+ sweep(baseDir: string): Promise<void>;+ standaloneVersion(release: StandaloneRelease, baseDir: string): string | null;+ installStandalone(release: StandaloneRelease, options: StandaloneInstallOptions): Promise<unknown>;+ handshake(command: string, args: readonly string[], env: NodeJS.ProcessEnv): Promise<string | null>;+}++const STEPS: UpdateSteps = {+ npmVersion: npmCopyVersion,+ npmLatest: npmLatestVersion,+ updateNpm: updateNpmEngineStaged,+ removeNpm: removeNpmCopy,+ sweep: sweepNpmLeftovers,+ standaloneVersion: standaloneCurrentVersion,+ installStandalone: installStandaloneEngine,+ handshake: acpHandshake,+};++export interface EngineUpdaterOptions {+ plans: readonly EnginePlan[];+ baseDir?: string;+ statePath: string;+ /** A turn is running somewhere on this server. */+ turnRunning(): boolean;+ /** The command lines of processes still running, to find one that runs an engine's copy. */+ liveCommands?(): Iterable<readonly string[]>;+ /** CLI paths set on engines: an npm copy one of them runs is kept. */+ configuredClis?(): readonly string[];+ /** After an update: engine statuses are read again. */+ updated?(): void;+ log?(line: string): void;+ now?(): number;+ steps?: Partial<UpdateSteps>;+ switchWait?: { forMs: number; everyMs: number };+}++interface EngineState {+ failures?: number;+ retryAt?: number;+ updatedTo?: string;+ updatedAt?: number;+}++interface UpdaterState {+ checkedAt: number | null;+ engines: Record<string, EngineState>;+}++type Outcome =+ | { kind: "absent" | "current" | "busy" | "waiting" }+ | { kind: "updated"; from: string; to: string }+ | { kind: "failed"; from: string; to: string; reason: string };++export interface EngineUpdater {+ /** One pass over every engine now; resolves when it has finished. */+ check(): Promise<void>;+ /** `autoUpdated` for an engine updated in the last week, for its row in Settings. */+ shown(driverKind: string): { autoUpdated?: { version: string; at: number } };+ /** The earliest time a pass is due. */+ dueAt(): number;+ start(): DueTimer;+}++function inside(path: string, root: string): boolean {+ const full = resolve(path);+ return full === root || full.startsWith(`${root}${sep}`);+}++function readState(path: string): UpdaterState {+ try {+ const raw = JSON.parse(readFileSync(path, "utf8")) as Partial<UpdaterState>;+ return {+ checkedAt: typeof raw.checkedAt === "number" ? raw.checkedAt : null,+ engines: raw.engines && typeof raw.engines === "object" ? raw.engines : {},+ };+ } catch {+ return { checkedAt: null, engines: {} };+ }+}++export function createEngineUpdater(options: EngineUpdaterOptions): EngineUpdater {+ const baseDir = options.baseDir ?? DATA_DIR;+ const steps: UpdateSteps = { ...STEPS, ...options.steps };+ const now = options.now ?? Date.now;+ const log = options.log ?? ((line: string) => console.warn(line));+ const switchWait = options.switchWait ?? { forMs: SWITCH_WAIT_MS, everyMs: SWITCH_POLL_MS };+ const state = readState(options.statePath);+ const startedAt = now();+ let passed = false;+ let busyRetryAt: number | null = null;+ let running: Promise<void> | null = null;++ const save = () => {+ try {+ mkdirSync(dirname(options.statePath), { recursive: true });+ writeFileAtomic(options.statePath, `${JSON.stringify(state)}\n`, { durable: false });+ } catch {}+ };++ /** The folders a copy of this engine lives in: a process whose command line reaches into one runs it. */+ const enginePaths = (plan: EnginePlan): string[] => {+ const npmPackages = [plan.npm, ...(plan.pin.formerNpm ?? [])].filter((pkg): pkg is string => Boolean(pkg));+ const modules = npmModulesIn(enginesPrefix(baseDir));+ return [+ ...npmPackages.map((pkg) => join(modules, ...pkg.split("/"))),+ ...(plan.cli ? [join(enginesBinDir(baseDir), plan.cli)] : []),+ ...(plan.standalone ? [standaloneEngineDir(plan.standalone.engine, baseDir)] : []),+ ...(plan.managed ? [plan.managed.folder] : []),+ ].map((path) => resolve(path));+ };++ /** A turn runs, or a process runs one of this engine's copies. */+ const engineInUse = (plan: EnginePlan): boolean => {+ if (options.turnRunning()) return true;+ const roots = enginePaths(plan);+ for (const line of options.liveCommands?.() ?? liveCliCommands()) {+ // A prefix match: Windows runs an npm command through `<name>.cmd` beside the path named here.+ if (line.some((part) => roots.some((root) => resolve(part).startsWith(root)))) return true;+ }+ return false;+ };++ /** In use, or an install from Settings is running npm for it. */+ const engineBusy = (plan: EnginePlan): boolean =>+ engineInUse(plan) || [plan.npm, ...(plan.pin.formerNpm ?? [])].some((pkg) => pkg && npmRunning(pkg, baseDir));++ /** Run just before a new copy takes over: it must answer the engine's handshake, and the engine must be free. */+ const beforeSwitch = (plan: EnginePlan, aborted: { busy: boolean }) => async (command: string): Promise<string | null> => {+ if (plan.pin.acp) {+ const env = { ...cliProbeEnvironment(), ...plan.standalone?.runEnv };+ stripControlPlaneEnv(env as Record<string, string | undefined>);+ const refused = await steps.handshake(command, plan.pin.acp, env);+ if (refused) return refused;+ }+ for (const until = now() + switchWait.forMs; engineInUse(plan);) {+ if (now() >= until) {+ aborted.busy = true;+ return "it is still in use";+ }+ await new Promise((resolveWait) => setTimeout(resolveWait, switchWait.everyMs).unref?.());+ }+ return null;+ };++ const configuredInto = (pkg: string): boolean => {+ const folder = resolve(join(npmModulesIn(enginesPrefix(baseDir)), ...pkg.split("/")));+ const commands = npmCommandNames(folder, pkg)+ .flatMap((name) => [name, `${name}.cmd`, `${name}.ps1`])+ .map((entry) => resolve(join(enginesBinDir(baseDir), entry)));+ return (options.configuredClis?.() ?? []).some((cli) => inside(cli, folder) || commands.includes(resolve(cli)));+ };++ async function updateStandalone(plan: EnginePlan, release: StandaloneRelease): Promise<Outcome> {+ const current = steps.standaloneVersion(release, baseDir);+ const npmCopies = [plan.npm, ...(plan.pin.formerNpm ?? [])]+ .filter((pkg): pkg is string => Boolean(pkg))+ .map((pkg) => ({ pkg, version: steps.npmVersion(pkg, baseDir) }))+ .filter((copy): copy is { pkg: string; version: string } => copy.version !== null);+ if (current === null && npmCopies.length === 0) return { kind: "absent" };+ const from = current ?? npmCopies[0]!.version;+ let outcome: Outcome = { kind: "current" };+ if (current === null || isNewerVersion(release.version, current)) {+ if (engineBusy(plan)) return { kind: "busy" };+ const aborted = { busy: false };+ try {+ await steps.installStandalone(release, { baseDir, beforeSwitch: beforeSwitch(plan, aborted) });+ } catch (error) {+ if (aborted.busy) return { kind: "waiting" };+ return { kind: "failed", from, to: release.version, reason: error instanceof Error ? error.message : String(error) };+ }+ outcome = { kind: "updated", from, to: release.version };+ }+ // The npm copies an earlier install left go only once the app's own build is in place, and never one a setting runs.+ for (const { pkg } of npmCopies) {+ if (engineBusy(plan) || configuredInto(pkg)) continue;+ await steps.removeNpm(pkg, baseDir).catch((error: unknown) => {+ if (!(error instanceof EngineInUse)) log(`Engine update: ${plan.name}'s old copy (${pkg}) could not be removed: ${error instanceof Error ? error.message : String(error)}`);+ });+ }+ return outcome;+ }++ async function updateNpm(plan: EnginePlan, pkg: string): Promise<Outcome> {+ const current = steps.npmVersion(pkg, baseDir);+ if (current === null) return { kind: "absent" };+ if (engineBusy(plan)) return { kind: "busy" };+ let target = plan.pin.target;+ if (target === LATEST) {+ try {+ target = await steps.npmLatest(pkg, baseDir);+ } catch (error) {+ return { kind: "failed", from: current, to: LATEST, reason: error instanceof Error ? error.message : String(error) };+ }+ }+ if (!isNewerVersion(target, current)) return { kind: "current" };+ const aborted = { busy: false };+ try {+ await steps.updateNpm({ pkg, version: target, baseDir, cli: plan.cli, beforeSwitch: beforeSwitch(plan, aborted) });+ } catch (error) {+ if (aborted.busy || error instanceof EngineInUse) return { kind: "waiting" };+ return { kind: "failed", from: current, to: target, reason: error instanceof Error ? error.message : String(error) };+ }+ return { kind: "updated", from: current, to: target };+ }++ async function updateManaged(plan: EnginePlan, managed: ManagedRuntime): Promise<Outcome> {+ const older = await managed.older();+ if (older === null) return { kind: "absent" };+ if (engineBusy(plan)) return { kind: "busy" };+ try {+ await managed.install();+ } catch (error) {+ return { kind: "failed", from: older, to: plan.pin.target, reason: error instanceof Error ? error.message : String(error) };+ }+ return { kind: "updated", from: older, to: plan.pin.target };+ }++ const updateOne = (plan: EnginePlan): Promise<Outcome> => {+ if (plan.standalone) return updateStandalone(plan, plan.standalone);+ if (plan.npm) return updateNpm(plan, plan.npm);+ if (plan.managed) return updateManaged(plan, plan.managed);+ return Promise.resolve({ kind: "absent" });+ };++ const retryDelay = (plan: EnginePlan, from: string, failures: number): number => {+ const cap = isNewerVersion(plan.pin.minimum, from) ? BELOW_MINIMUM_RETRY_CAP_MS : ENGINE_UPDATE_EVERY_MS;+ return Math.min(cap, FIRST_RETRY_MS * 2 ** Math.min(failures - 1, 10));+ };++ async function pass(): Promise<void> {+ await steps.sweep(baseDir).catch(() => {});+ let waiting = false;+ let changed = false;+ for (const plan of options.plans) {+ const engine = state.engines[plan.driverKind] ?? {};+ if (engine.retryAt !== undefined && engine.retryAt > now()) continue;+ let outcome: Outcome;+ try {+ outcome = await updateOne(plan);+ } catch (error) {+ outcome = { kind: "failed", from: "?", to: plan.pin.target, reason: error instanceof Error ? error.message : String(error) };+ }+ if (outcome.kind === "busy" || outcome.kind === "waiting") waiting = true;+ if (outcome.kind === "updated") {+ state.engines[plan.driverKind] = { updatedTo: outcome.to, updatedAt: now() };+ log(`Engine update: ${plan.name} ${outcome.from} → ${outcome.to}`);+ changed = true;+ } else if (outcome.kind === "failed") {+ const failures = (engine.failures ?? 0) + 1;+ state.engines[plan.driverKind] = { ...engine, failures, retryAt: now() + retryDelay(plan, outcome.from, failures) };+ log(`Engine update: ${plan.name} stays on ${outcome.from}; ${outcome.to} could not be installed (${outcome.reason.split("\n")[0]}). Trying again later.`);+ } else if (engine.failures) {+ state.engines[plan.driverKind] = { updatedTo: engine.updatedTo, updatedAt: engine.updatedAt };+ }+ }+ passed = true;+ busyRetryAt = waiting ? now() + ENGINE_UPDATE_BUSY_RETRY_MS : null;+ if (!waiting) state.checkedAt = now();+ save();+ if (changed) options.updated?.();+ }++ const dueAt = (): number => {+ if (!passed) return startedAt + ENGINE_UPDATE_START_DELAY_MS;+ const times = [(state.checkedAt ?? startedAt) + ENGINE_UPDATE_EVERY_MS];+ if (busyRetryAt !== null) times.push(busyRetryAt);+ for (const engine of Object.values(state.engines)) if (engine.failures && engine.retryAt !== undefined) times.push(engine.retryAt);+ return Math.min(...times);+ };++ const check = (): Promise<void> => {+ running ??= pass().finally(() => { running = null; });+ return running;+ };++ return {+ check,+ dueAt,+ shown(driverKind) {+ const engine = state.engines[driverKind];+ return engine?.updatedTo && engine.updatedAt !== undefined && now() - engine.updatedAt < SHOW_UPDATED_MS+ ? { autoUpdated: { version: engine.updatedTo, at: engine.updatedAt } }+ : {};+ },+ start() {+ return startDueTimer({+ now,+ next: dueAt,+ retryMs: ENGINE_UPDATE_BUSY_RETRY_MS,+ run: () => (now() >= dueAt() ? check() : undefined),+ onError: (error) => log(`Engine update: ${error instanceof Error ? error.message : String(error)}`),+ });+ },+ };+}diff --git a/server/engine-versions.ts b/server/engine-versions.tsnew file mode 100644index 0000000000..34a26226f9--- /dev/null+++ b/server/engine-versions.ts@@ -0,0 +1,45 @@+// The engine versions this release was tested with, for the copies the app installs itself (npm into tools/npm, the+// vendors' own builds into tools/standalone, Antigravity's runtime into tools/antigravity-acp). Settings' Install gives+// these versions and the updater moves older copies up to them, never past them. Each npm version below was installed+// on 2026-11-07 into a staging prefix, moved into place, and answered `--version` (and, for an ACP engine, `initialize`)+// from there; OpenCode 1.19.4 sessions, sign-ins and settings were opened by 2.2.5 the same day.+import { ANTIGRAVITY_RELEASE_VERSION } from "./drivers/antigravity-release.ts";+import { CURSOR_STANDALONE } from "./drivers/acp/cursor-release.ts";+import { OPENCODE_STANDALONE } from "./drivers/acp/opencode-release.ts";++/** Claude Code follows its vendor's newest release, as its own updater does. */+export const LATEST = "latest";++export interface EngineVersionPin {+ /** The version Install gives and the updater moves to, or LATEST. */+ target: string;+ /** The oldest version this release's driver is known to work with; the target when no older one was checked. A copy+ * below it is retried sooner after a failed update. */+ minimum: string;+ /** The arguments that start the engine's ACP server: a new copy must answer `initialize` there before it replaces one. */+ acp?: readonly string[];+ /** npm packages earlier releases installed this engine as, into the app's npm folder; the app's own build replaces them. */+ formerNpm?: readonly string[];+}++export const ENGINE_VERSIONS: Readonly<Record<string, EngineVersionPin>> = {+ claudeAgent: { target: LATEST, minimum: "2.1.267" },+ codex: { target: "0.167.0", minimum: "0.146.0" },+ geminiAgent: { target: "0.67.0", minimum: "0.67.0", acp: ["--acp"] },+ kimiAgent: { target: "2.5.2", minimum: "2.4.1", acp: ["acp"] },+ clineAgent: { target: "3.0.74", minimum: "3.0.70", acp: ["--acp", "--auto-approve", "false"] },+ copilotAgent: { target: "1.0.106", minimum: "1.0.103", acp: ["--acp", "--stdio"] },+ commandCodeAgent: { target: "1.88.4", minimum: "1.88.4", acp: ["acp"] },+ piAgent: { target: "1.5.0", minimum: "1.5.0" },+ minimax: { target: "1.0.28", minimum: "1.0.28" },+ deepseekAgent: { target: "0.2.2-rc.1", minimum: "0.2.1-rc.2", acp: ["--profile", "acp"] },+ opencodeGo: { target: OPENCODE_STANDALONE.version, minimum: "1.19.4", acp: ["acp"], formerNpm: ["opencode-ai"] },+ cursorAgent: { target: CURSOR_STANDALONE.version, minimum: CURSOR_STANDALONE.version },+ antigravityAgent: { target: ANTIGRAVITY_RELEASE_VERSION, minimum: ANTIGRAVITY_RELEASE_VERSION },+};++/** The exact npm version Install asks for; undefined follows npm's `latest` tag. */+export function pinnedNpmVersion(driverKind: string): string | undefined {+ const target = ENGINE_VERSIONS[driverKind]?.target;+ return target && target !== LATEST ? target : undefined;+}diff --git a/server/harness/registry.ts b/server/harness/registry.tsindex 38b33fe287..36cc2eee6d 100644--- a/server/harness/registry.ts+++ b/server/harness/registry.ts@@ -2,6 +2,7 @@import { findCliCandidates } from "../env-path.ts";import { installNpmEngine, npmAvailable, serverInstallFor, standaloneLookupPath } from "../engine-install.ts";import { installStandaloneEngine, isAppStandaloneCopy, type StandaloneInstalled } from "../engine-standalone.ts";+import { pinnedNpmVersion } from "../engine-versions.ts";import { withEngineMemory } from "../engine-memory.ts";import { withEngineHomes } from "../engine-homes/engine-homes.ts";import { withLocalContext } from "../drivers/local-inject.ts";@@ -345,7 +346,7 @@ export class ProviderRegistry {return (await this.appCopyAdvice(instanceId, driver, installed)) ?? true;}if (!server?.package) return false;- await installNpmEngine(server.package, { baseDir: this.enginesBaseDir, cli: cliDefaultOf(driver) });+ await installNpmEngine(server.package, { baseDir: this.enginesBaseDir, cli: cliDefaultOf(driver), version: driver ? pinnedNpmVersion(driver.driverKind) : undefined });return true;} finally {this.forgetSnapshots();diff --git a/server/index.ts b/server/index.tsindex 502730c74b..09a3e117b8 100644--- a/server/index.ts+++ b/server/index.ts@@ -189,7 +189,7 @@ import { serveStatic } from "./static-files.ts";import { startUpkeep } from "./host/start-upkeep.ts";import { ComputerControl } from "./computer-control.ts";import { resetPathCache } from "./env-path.ts";-import { registerEnginesBinDir } from "./engine-install.ts";+import { registerEnginesBinDir } from "./engine-install.ts"; import { engineUpdatesFor } from "./engine-updates-host.ts";import { appendUsage, flushUsageLedger, queuedTurnTrigger, usageTriggerFor, type UsageRow, type UsageTrigger } from "./usage-ledger.ts"; import { createUsageAttribution } from "./usage-attribution.ts";import { createTraceRecorder } from "./usage-trace/recorder.ts";import { GroupUsageReader } from "./group-thread-usage.ts";@@ -813,7 +813,7 @@ function customDomainStatus() {}const registry = new ProviderRegistry(BUILT_IN_DRIVERS, { statusFile: join(DATA_DIR, "providers", "engine-status.json") });const supportsApprovalMode = createApprovalModeSupport(registry);-registerEnginesBinDir();+registerEnginesBinDir(); const engineUpdates = engineUpdatesFor({ drivers: BUILT_IN_DRIVERS, turnRunning: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking) || Boolean(routines?.hasActiveRuns()), configuredClis: () => Object.values(providerConfigs()).flatMap((entry) => { const cli = (entry.config as { cli?: unknown } | undefined)?.cli; return typeof cli === "string" && cli ? [cli] : []; }), updated: () => { registry.forgetSnapshots(); broadcast({ kind: "config", ...configStatus() }); } });// Set only when a turn is admitted, never on queue or steer, so a second person's words cannot re-book the first person's turn.const turnTriggers = new Map<string, UsageTrigger>();@@ -11887,7 +11887,7 @@ async function describeInstances() {return engines.map((instance) => {const entry = configs[instance.instanceId];const described = {- ...instance, ...testedAi.info(instance),+ ...instance, ...testedAi.info(instance), ...engineUpdates.shown(instance.driverKind),...instanceIcon(entry),...(entry?.access ? { access: entry.access } : {}), ...(entry?.driver === "openai-compat" && typeof (entry.config as { replyWaitMinutes?: unknown } | undefined)?.replyWaitMinutes === "number" ? { replyWaitMinutes: (entry.config as { replyWaitMinutes: number }).replyWaitMinutes } : {}), ...(heldKeys?.refusal(instance.instanceId) ? { snapshot: { state: "unavailable" as const, reason: TRIAL_KEY_HELD } } : {}),};@@ -15518,7 +15518,7 @@ server.listen(PORT, "127.0.0.1", async () => {console.log(`openmausbot server on http://127.0.0.1:${PORT}`);personWaits.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });void afterFirstEngineRead().then(() => { if (builtInBrowserEnabled(cfg)) chromeLauncher.start(); });- followupsReady = true;+ followupsReady = true; engineUpdates.start();drainQueuedSends();drainQueuedChannelSends();void cloudComputerPower.armRunning();diff --git a/server/procs.ts b/server/procs.tsindex ef2de4d7ba..3b79e77f8e 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -153,6 +153,19 @@ function rememberEngineSession(child: ChildProcess): void {});}+const liveSpawns = new Set<readonly string[]>();++/** The command line of every process spawnCli started that has not exited yet. */+export function liveCliCommands(): Iterable<readonly string[]> {+ return liveSpawns;+}++function rememberLiveSpawn(child: ChildProcess, line: readonly string[]): void {+ if (!child.pid) return;+ liveSpawns.add(line);+ child.once("exit", () => liveSpawns.delete(line));+}+/** `bot`: an engine running bots' turns, whose own servers that bot's browser may open on a server host.* `openmausbot`: everything else (logins, probes, the browser engine itself). */export type CliOwner = "bot" | "openmausbot";@@ -203,6 +216,7 @@ export function spawnCli(} finally {for (const fd of boxed?.extraFds ?? []) try { closeSync(fd); } catch {}}+ rememberLiveSpawn(child, [resolved.command, ...resolved.args]);// The broker token minted for this process dies with it.if (boxed?.token) child.once("exit", boxed.release);if (process.platform !== "win32") cliGroups.add(child);diff --git a/src/components/EngineLibrary.tsx b/src/components/EngineLibrary.tsxindex c749510034..03b74449e8 100644--- a/src/components/EngineLibrary.tsx+++ b/src/components/EngineLibrary.tsx@@ -1,4 +1,5 @@import { useState, type ReactNode } from "react";+import { useUpdatedOnce } from "@/hooks/use-updated-once";import { ArrowUpRight, Check, ChevronDown, RefreshCw } from "lucide-react";import { useStore, type InstanceInfo } from "@/state/store";import { cn } from "@/lib/cn";@@ -38,6 +39,7 @@ export function EngineCard({ instance, children, summary, bare = false }: { inst: providerName(instance));// Some CLIs return their executable name rather than a version.const version = instance.snapshot.version?.match(/\d+\.\d+(?:\.\d+)?(?:[-+][\w.-]+)?/)?.[0];+ const updatedTo = useUpdatedOnce(instance);return (<details data-engine-card={instance.instanceId} className="group/engine min-w-0 rounded-2xl border border-hairline/40 bg-card transition-colors open:col-span-full open:border-hairline/70 hover:border-hairline/70"><summary className="cursor-pointer list-none rounded-2xl p-4 outline-none focus-visible:ring-2 focus-visible:ring-accent [&::-webkit-details-marker]:hidden">@@ -60,7 +62,7 @@ export function EngineCard({ instance, children, summary, bare = false }: { inst{summary ? (<span className={cn("text-[11px] font-medium", ready ? "text-ink-secondary" : "text-accent-text")}>{summary.action}</span>) : ready ? (- <span className="text-[11px] tabular-nums text-ink-secondary">{version ? `v${version}` : t("engines.library.manage")}</span>+ <span className="text-[11px] tabular-nums text-ink-secondary">{updatedTo ? t("engines.updatedTo", { version: updatedTo }) : version ? `v${version}` : t("engines.library.manage")}</span>) : (<span className="inline-flex items-center gap-1 text-[12px] font-semibold text-accent-text">{t("engines.library.setup")}<ArrowUpRight size={13} aria-hidden="true" />diff --git a/src/hooks/use-updated-once.dom.test.ts b/src/hooks/use-updated-once.dom.test.tsnew file mode 100644index 0000000000..d664428aa6--- /dev/null+++ b/src/hooks/use-updated-once.dom.test.ts@@ -0,0 +1,39 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { useUpdatedOnce } from "./use-updated-once";++let root: Root | null = null;+let container: HTMLElement | null = null;+beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ const stored = new Map<string, string>();+ vi.stubGlobal("localStorage", { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) });+});+afterEach(async () => {+ await act(async () => root?.unmount());+ container?.remove();+ root = null;+ vi.unstubAllGlobals();+});++async function shownFor(autoUpdated?: { version: string; at: number }): Promise<string> {+ function Card() {+ return createElement("span", null, useUpdatedOnce({ driverKind: "opencodeGo", autoUpdated }) ?? "plain");+ }+ await act(async () => root?.unmount());+ container?.remove();+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ await act(async () => root!.render(createElement(Card)));+ return container.textContent ?? "";+}++it("names the version the app updated an engine to the first time its card shows, then no more", async () => {+ expect(await shownFor()).toBe("plain");+ expect(await shownFor({ version: "2.2.5", at: 1 })).toBe("2.2.5");+ expect(await shownFor({ version: "2.2.5", at: 1 })).toBe("plain");+ expect(await shownFor({ version: "2.3.0", at: 2 })).toBe("2.3.0");+});diff --git a/src/hooks/use-updated-once.ts b/src/hooks/use-updated-once.tsnew file mode 100644index 0000000000..05f18e2d41--- /dev/null+++ b/src/hooks/use-updated-once.ts@@ -0,0 +1,28 @@+import { useEffect, useState } from "react";+import type { InstanceInfo } from "@/state/store";++const SEEN_KEY = "omb-engine-updated-seen";++function seen(): Record<string, string> {+ try {+ const value = JSON.parse(localStorage.getItem(SEEN_KEY) ?? "{}") as unknown;+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, string> : {};+ } catch {+ return {};+ }+}++/** The version the app updated this engine to, from the first time this device shows its card after the update until+ * the card goes away; null otherwise. */+export function useUpdatedOnce(instance: Pick<InstanceInfo, "driverKind" | "autoUpdated">): string | null {+ const version = instance.autoUpdated?.version ?? null;+ const [shown, setShown] = useState<string | null>(null);+ useEffect(() => {+ if (version === null || seen()[instance.driverKind] === version) return;+ setShown(version);+ try {+ localStorage.setItem(SEEN_KEY, JSON.stringify({ ...seen(), [instance.driverKind]: version }));+ } catch {}+ }, [instance.driverKind, version]);+ return shown;+}diff --git a/src/locales/de.json b/src/locales/de.jsonindex ad1bd78cce..ea52ac4425 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -1526,6 +1526,7 @@"engines.resetting": "Wird zurückgesetzt…","engines.setCli": "CLI festlegen…","engines.claudeUpdated": "Claude aktualisiert — {version}",+ "engines.updatedTo": "Aktualisiert auf {version}","engines.account.signInHint": "Führe genau diesen Befehl in einem Terminal auf dem Computer aus, auf dem {app} läuft, schließe die Claude-CLI-Anmeldung ab und klicke dann auf „Konto prüfen“. Wenn du {app} aus der Ferne nutzt, führe ihn dort aus, nicht auf diesem Gerät.","engines.none": "Bisher keine Apps von Modellanbietern erkannt.","remote.pairing.tailscale.title": "Tailscale-Kopplung",diff --git a/src/locales/en.json b/src/locales/en.jsonindex ab7f2c05f1..54422481e9 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -4369,6 +4369,7 @@"engines.unhide": "Unhide","engines.unhiding": "Unhiding…","engines.claudeUpdated": "Claude updated to {version}",+ "engines.updatedTo": "Updated to {version}","engines.account.signInHint": "Run this exact command in a terminal on the computer running {app}, finish Claude CLI sign-in, then click Check account. If you are viewing {app} remotely, run it there, not on this device.","engines.account.powershell": "Use PowerShell for this command.","accounts.claude": "Claude",diff --git a/src/locales/es.json b/src/locales/es.jsonindex 1181377a4d..ca73af7091 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -3418,6 +3418,7 @@"engines.resetting": "Restableciendo…","engines.setCli": "Definir CLI…","engines.claudeUpdated": "Claude actualizado: {version}",+ "engines.updatedTo": "Actualizado a {version}","engines.account.signInHint": "Ejecuta este comando exacto en una terminal del equipo donde se ejecuta {app}, completa el inicio de sesión de Claude CLI y luego haz clic en «Comprobar cuenta». Si estás viendo {app} de forma remota, ejecútalo allí, no en este dispositivo.","engines.account.powershell": "Usa PowerShell para este comando.","accounts.claude": "Claude",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex a5a6553f2d..f7e693641b 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -1470,6 +1470,7 @@"engines.resetting": "Réinitialisation…","engines.setCli": "Définir la CLI…","engines.claudeUpdated": "Claude mis à jour — {version}",+ "engines.updatedTo": "Mis à jour vers {version}","engines.account.signInHint": "Exécutez exactement cette commande dans un terminal sur l’ordinateur qui exécute {app}, terminez la connexion Claude CLI, puis cliquez sur « Vérifier le compte ». Si vous consultez {app} à distance, exécutez-la là-bas, pas sur cet appareil.","engines.none": "Aucune application de fournisseur de modèles détectée pour l’instant.","remote.pairing.tailscale.title": "Appairage via Tailscale",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex 50c60f5811..680aefe221 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -1470,6 +1470,7 @@"engines.resetting": "रीसेट हो रहा है…","engines.setCli": "CLI सेट करें…","engines.claudeUpdated": "Claude अपडेट हुआ — {version}",+ "engines.updatedTo": "{version} पर अपडेट हुआ","engines.account.signInHint": "{app} चला रहे कंप्यूटर के टर्मिनल में यही कमांड चलाएँ, Claude CLI साइन-इन पूरा करें, फिर खाता जाँचें पर क्लिक करें। अगर आप {app} को रिमोट से देख रहे हैं, तो इसे वहीं चलाएँ, इस डिवाइस पर नहीं।","engines.none": "अभी कोई मॉडल प्रदाता ऐप नहीं मिला।","remote.pairing.tailscale.title": "Tailscale से जोड़ना",diff --git a/src/locales/it.json b/src/locales/it.jsonindex 0235a95a11..2e8c1e6de0 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -3667,6 +3667,7 @@"engines.resetting": "Reimpostazione…","engines.setCli": "Imposta CLI…","engines.claudeUpdated": "Claude aggiornato — {version}",+ "engines.updatedTo": "Aggiornato a {version}","engines.account.signInHint": "Esegui questo comando esatto in un terminale sul computer dove è in esecuzione {app}, completa l'accesso alla CLI Claude, poi fai clic su Controlla account. Se stai vedendo {app} da remoto, eseguilo lì, non su questo dispositivo.","engines.account.powershell": "Usa PowerShell per questo comando.","accounts.count": "{count} account · {signedIn} con accesso effettuato",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex edd4f74d59..4b0c04330c 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -4212,6 +4212,7 @@"engines.unhide": "再表示","engines.unhiding": "再表示しています…","engines.claudeUpdated": "Claude を更新しました — {version}",+ "engines.updatedTo": "{version} に更新しました","engines.account.signInHint": "{app} が動いているコンピューターのターミナルで、このコマンドをそのまま実行し、Claude CLI のサインインを完了してから「アカウントを確認」をクリックしてください。{app} をリモートで開いている場合は、このデバイスではなくそちらで実行してください。","engines.account.powershell": "このコマンドには PowerShell を使ってください。","accounts.claude": "Claude",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex 0a2770d92b..6dd62afd20 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -4035,6 +4035,7 @@"engines.resetting": "초기화 중…","engines.setCli": "CLI 지정…","engines.claudeUpdated": "Claude 업데이트됨 — {version}",+ "engines.updatedTo": "{version}(으)로 업데이트됨","engines.account.signInHint": "{app}이 실행 중인 컴퓨터의 터미널에서 이 명령을 그대로 실행하고 Claude CLI 로그인을 마친 뒤 계정 확인을 누르세요. {app}을 원격으로 보고 있다면 이 기기가 아니라 그 컴퓨터에서 실행하세요.","engines.account.powershell": "이 명령은 PowerShell에서 실행하세요.","accounts.claude": "Claude",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 6ec1fadc11..59917d3637 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -3730,6 +3730,7 @@"engines.resetting": "Resetowanie…","engines.setCli": "Ustaw CLI…","engines.claudeUpdated": "Claude zaktualizowano — {version}",+ "engines.updatedTo": "Zaktualizowano do {version}","engines.account.signInHint": "Uruchom dokładnie tę komendę w terminalu na komputerze, na którym działa {app}, dokończ logowanie do Claude CLI, a następnie kliknij Sprawdź konto. Jeśli łączysz się z {app} zdalnie, uruchom ją tam, a nie na tym urządzeniu.","engines.account.powershell": "Użyj PowerShell dla tej komendy.","accounts.claude": "Claude",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 52cea2c1a1..7dbe456ddf 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -4112,6 +4112,7 @@"engines.unhide": "Mostrar novamente","engines.unhiding": "Mostrando novamente…","engines.claudeUpdated": "Claude atualizado para {version}",+ "engines.updatedTo": "Atualizado para {version}","engines.account.signInHint": "Execute exatamente este comando no terminal do computador onde o app {app} roda, conclua o login na CLI do Claude e clique em Verificar conta. Se você acessa o app {app} remotamente, execute lá, não neste dispositivo.","engines.account.powershell": "Use o PowerShell para este comando.","accounts.claude": "Claude",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex f633d21ae8..8e5359193a 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -3786,6 +3786,7 @@"engines.resetting": "Сброс…","engines.setCli": "Указать CLI…","engines.claudeUpdated": "Claude обновлён — {version}",+ "engines.updatedTo": "Обновлено до {version}","engines.account.signInHint": "Выполните эту точную команду в терминале на компьютере, где работает {app}, завершите вход Claude CLI, затем нажмите «Проверить аккаунт». Если вы открываете {app} удалённо, выполните её там, а не на этом устройстве.","engines.account.powershell": "Для этой команды используйте PowerShell.","accounts.claude": "Claude",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 74c8956f6a..df187120f4 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -3079,6 +3079,7 @@"engines.resetting": "Sıfırlanıyor…","engines.setCli": "CLI'ı Ayarla…","engines.claudeUpdated": "Claude güncellendi — {version}",+ "engines.updatedTo": "{version} sürümüne güncellendi","engines.account.signInHint": "Bu komutu aynen {app}'u çalıştıran bilgisayardaki terminalde çalıştırın, Claude CLI girişini tamamlayın ve ardından Hesabı kontrol et'e tıklayın. {app}'u uzaktan görüntülüyorsanız bu cihazda değil orada çalıştırın.","engines.account.powershell": "Bu komut için PowerShell kullanın.","accounts.claude": "Claude",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex bcc5cbc489..08468dd759 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -1776,6 +1776,7 @@"engines.resetting": "Скидаємо…","engines.setCli": "Задати CLI…","engines.claudeUpdated": "Claude оновлено — {version}",+ "engines.updatedTo": "Оновлено до {version}","engines.account.signInHint": "Виконайте цю команду в терміналі на комп'ютері, де працює {app}, завершіть вхід Claude CLI, потім натисніть «Перевірити акаунт». Якщо ви дивитеся {app} віддалено, запускайте там, а не на цьому пристрої.","engines.account.powershell": "Для цієї команди використайте PowerShell.","engines.none": "Застосунків провайдерів моделей ще не виявлено.",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 5ba95abdc0..1b1b57cdd5 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -3079,6 +3079,7 @@"engines.resetting": "Đang đặt lại…","engines.setCli": "Thiết lập CLI…","engines.claudeUpdated": "Đã cập nhật Claude — {version}",+ "engines.updatedTo": "Đã cập nhật lên {version}","engines.account.signInHint": "Chạy chính xác lệnh này trong terminal trên máy tính đang chạy {app}, hoàn tất đăng nhập Claude CLI, sau đó nhấp vào Kiểm tra tài khoản. Nếu bạn đang xem {app} từ xa, hãy chạy lệnh ở đó, không phải trên thiết bị này.","engines.account.powershell": "Sử dụng PowerShell cho lệnh này.","accounts.claude": "Claude",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 9c23a0378e..6c177a3391 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -2630,6 +2630,7 @@"engines.resetting": "重設中…","engines.setCli": "設定 CLI…","engines.claudeUpdated": "Claude 已更新 — {version}",+ "engines.updatedTo": "已更新到 {version}","engines.account.signInHint": "請在執行 {app} 的電腦終端機中執行這道完整指令,完成 Claude CLI 登入後,再點選「檢查帳戶」。若你是以遠端方式檢視 {app},請在那裡執行,而不是這台裝置。","engines.account.powershell": "這道指令請使用 PowerShell 執行。","engines.none": "尚未偵測到任何模型供應商應用程式。",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex a3021fa449..6cc9873d1e 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -4186,6 +4186,7 @@"engines.resetting": "正在重置…","engines.setCli": "设置命令行…","engines.claudeUpdated": "Claude 已更新——{version}",+ "engines.updatedTo": "已更新到 {version}","engines.account.signInHint": "请在运行 {app} 的电脑终端中运行这条完整指令,完成 Claude CLI 登录后,再点击「检查账户」。若你是以远程方式查看 {app},请在那里运行,而不是这台设备。","engines.account.powershell": "这道指令请使用 PowerShell 运行。","accounts.claude": "Claude",diff --git a/src/state/store.tsx b/src/state/store.tsxindex 908f842ee3..f99734d4b8 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -506,7 +506,7 @@ export interface InstanceInfo extends InstanceEndpointInfo {cliDefault?: string;cliCandidates?: string[];claudeAccount?: { configDir: string; signInCommand: string; signInShell: "powershell" | "sh"; isDefault: boolean };- freeUpSpace?: boolean; replyWaitMinutes?: number; modelsUnconfirmed?: true;+ freeUpSpace?: boolean; replyWaitMinutes?: number; modelsUnconfirmed?: true; /** The app updated its own copy of this engine to this version lately. */ autoUpdated?: { version: string; at: number };}export type AppSettingsSection =