Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
import { lstatSync, readdirSync, readlinkSync, realpathSync, type Stats } from "node:fs";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { parseStoredConfig } from "./config.ts";
import { inSecretFolder } from "./secret-folder.ts";
// Connection sections stay on the destination whole: a restored URL must never redirect an API key kept from that device.
const PORTABLE_CONFIG_KEYS = [
"profile", "language", "budgets", "billing", "rooms", "threads",
"localVm", "features", "browserProfiles",
] as const;
export function portableWorkspaceConfig(value: unknown): Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid workspace configuration in backup.");
const config = parseStoredConfig(value as Parameters<typeof parseStoredConfig>[0]);
return {
...Object.fromEntries(PORTABLE_CONFIG_KEYS.filter((key) => config[key] !== undefined).map((key) => [key, config[key]])),
...(config.threadTitles?.followUp === undefined ? {} : { threadTitles: { followUp: config.threadTitles.followUp } }),
};
}
// Computer sharing opens routes and a desktop connector here: a restore never turns it on or off.
const DESTINATION_FEATURES = ["sharedComputers"] as const;
export function restoredWorkspaceConfig(portable: unknown, destination: unknown): Record<string, unknown> {
if (!destination || typeof destination !== "object" || Array.isArray(destination)) throw new Error("Invalid destination workspace configuration; connections were not changed.");
const merged = { ...destination } as Record<string, unknown>;
for (const key of PORTABLE_CONFIG_KEYS) delete merged[key];
delete merged.threadTitles;
const restored = { ...merged, ...portableWorkspaceConfig(portable) };
const model = (destination as { threadTitles?: { model?: unknown } }).threadTitles?.model;
if (model !== undefined) restored.threadTitles = { ...(restored.threadTitles as object | undefined), model };
const own = (destination as { features?: Record<string, unknown> }).features ?? {};
const features: Record<string, unknown> = { ...(restored.features as Record<string, unknown> | undefined) };
for (const key of DESTINATION_FEATURES) {
delete features[key];
if (own[key] !== undefined) features[key] = own[key];
}
if (Object.keys(features).length) restored.features = features;
else delete restored.features;
return restored;
}
export function excludedWorkspaceAuthPath(path: string): boolean {
if (inSecretFolder(path)) return true;
if (/^command-allowlist\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;
if (/^mcp-oauth\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;
// A "Sign in with Boat" connection kept by an app run from source: like the pasted key, it never leaves this computer.
if (/^boat-sign-in\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;
// Bot API keys saved for teammates on other servers stay on the server they were saved on, like any other credential.
if (/^remote-teammates\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;
// Saved website logins and their key never leave the computer they were saved on, nor does the key sealing webhook secrets.
if (/^(?:logins\.json\.enc|member-secrets\.json\.enc|logins-key|webhook-key)(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;
// A Cloud home's connected-apps installation: its connected accounts belong to it, so a copy would share them.
if (/^connected-apps-installation\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;
// A Team Cloud's kept rules: a restored Cloud asks the Admin for the ones in force now.
if (/^team-policy\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;
// A Team Cloud member's own installation, keys and sign-ins: theirs, never in the team's backup.
if (/^people-connections(?:\/|$)/.test(path)) return true;
// GitHub sign-ins (github/sign-in.ts): each holds its token in plain text for GitHub CLI, and stays on this server.
if (/^github(?:\/|$)/.test(path)) return true;
// A dated copy of the settings file, and the copy of one that could not be understood: they hold the credentials
// the settings file holds, so they never leave the computer they were taken on.
if (/^config\.json\.(?:bak\.\d{8}-\d{6}(?:-\d+)?|unreadable-[0-9a-f]{12})(?:\.\d+\.[0-9a-f-]+\.tmp)?$/.test(path)) return true;
return /^(?:(?:providers|caddy|chrome-profile|\.agent-browser)(?:\/|$)|workspace-credentials\.json$|external-runtimes\.json$|browser-engine-key$)/.test(path) ||
/^(?:config\.json|webhooks\.json|workspace-credentials\.json|external-runtimes\.json|browser-engine-key|sessions\.json|tunnel-account\.json)\.\d+(?:\.[0-9a-f-]+)?\.tmp$/.test(path) ||
/^(?:vm-home|vm-homes\/[^/]+)\/\.browser-profiles(?:\/|$)/.test(path);
}
export function redownloadedOrgLibraryPath(path: string): boolean {
return /^org-library\/(?:catalog\.json(?:\.[0-9a-f-]{36}\.tmp)?$|blobs(?:\/|$))/.test(path);
}
export function ephemeralWorkspaceTokenPath(path: string): boolean {
return /^(?:hook-tokens(?:\/|$)|sessions\.json\.open$)/.test(path);
}
/** DuckDB's spill folder for a bot's Data tables: scratch space for one query, emptied when the database closes. The
* database itself (data.duckdb) goes, taken at rest (workspace-backup-databases.ts). */
export function dataEngineSpillPath(path: string): boolean {
return /^bots\/[^/]+\/data-tmp(?:\/|$)/.test(path);
}
/** Read the link text, never follow it. A link points at the bot's own skill, or at the same-named skill brought in
* from this computer (imported-skills.ts), which the backup carries. */
export function managedTaskSkillLink(source: string, path: string, roots: string[]): boolean {
const match = /^task-workspaces\/([^/]+)\/[^/]+\/\.(?:claude|agents|grok)\/skills\/([^/]+)$/.exec(path);
if (!match) return false;
let target: string;
try { target = resolve(dirname(source), readlinkSync(source).replace(/^\\\\\?\\/, "")); } catch { return false; }
return roots.some((root) => {
const rel = relative(join(root, "workspaces", match[1], "skills"), target);
return (rel !== "" && !rel.startsWith("..") && !isAbsolute(rel)) || relative(join(root, "imported-skills", match[2]), target) === "";
});
}
/** A folder a project installs and can install again, never carried: node_modules, and a Python virtual environment (any
* folder holding pyvenv.cfg, as `python -m venv`, virtualenv, uv and Poetry make them), whose bin/python links to the
* Python it was made with, outside the workspace. Either may itself be a link. */
export function installedDependencyFolder(source: string, name: string, stat: Stats): boolean {
if (!stat.isDirectory() && !stat.isSymbolicLink()) return false;
if (name === "node_modules") return true;
try { return lstatSync(join(source, "pyvenv.cfg")).isFile(); } catch { return false; }
}
/** A Chromium browser's own profile folder (it holds "Local State"), as a bot's project may keep one: its sign-ins and
* cookies stay on the computer they were made on, as the app's own browser profiles do, and its caches are large. */
export function browserProfileFolder(source: string, stat: Stats): boolean {
if (!stat.isDirectory()) return false;
try { return lstatSync(join(source, "Local State")).isFile(); } catch { return false; }
}
/** Up to three of `paths`, for a note that names what was left out. */
export const examplePaths = (paths: readonly string[]): string => `${paths.slice(0, 3).join(", ")}${paths.length > 3 ? ", …" : ""}`;
/** Python's bytecode cache, written again the next time the code runs. */
export const bytecodeCache = (name: string, stat: Stats): boolean => name === "__pycache__" && (stat.isDirectory() || stat.isSymbolicLink());
/** `path` relative to `folder`, or undefined when it is not inside it. */
export function pathUnder(folder: string, path: string): string | undefined {
const rel = relative(folder, path);
return rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel) ? undefined : rel;
}
/** A top-level item of the data folder that links to another place (a folder moved to another drive, a Windows
* junction): the backup follows it, and what is under its target counts as under its name. */
export type FollowedTopLevelLink = { name: string; target: string };
/** Where `target` is in the data folder `root`, also through a followed top-level link; undefined when outside both. */
export function dataRelativePath(root: string, followed: readonly FollowedTopLevelLink[], target: string): string | undefined {
return dataRelativePaths(root, followed, target, false)[0];
}
/** Every path under which the data folder `root` carries `target`: its own path, its path under each followed top-level
* link that holds it, and, with `linksInside`, the name of each followed link that points inside it. */
export function dataRelativePaths(root: string, followed: readonly FollowedTopLevelLink[], target: string, linksInside: boolean): string[] {
const own = pathUnder(root, target);
const paths = own === undefined ? [] : [own];
for (const link of followed) {
const inside = pathUnder(link.target, target);
if (inside !== undefined) paths.push(inside ? join(link.name, inside) : link.name);
else if (linksInside && pathUnder(target, link.target) !== undefined) paths.push(link.name);
}
return paths;
}
/** True when a new top-level link points at or above a place already followed, which would carry it twice. */
export function carriedTwice(followed: readonly FollowedTopLevelLink[], target: string): boolean {
return followed.some((link) => pathUnder(target, link.target) !== undefined);
}
/** The top-level items of the data folder `root` (its real path) that link to a place outside it, as the backup follows
* them. Read before the walk, so a link into one of them is judged the same whatever the names sort like. A dangling
* link, or one to a folder holding `root`, is left out here; the backup itself refuses both. */
export function topLevelLinksOut(root: string): FollowedTopLevelLink[] {
const links: FollowedTopLevelLink[] = [];
for (const name of readdirSync(root)) {
const source = join(root, name);
if (!lstatSync(source).isSymbolicLink()) continue;
let target: string;
try { target = realpathSync(source); } catch { continue; }
if (pathUnder(root, target) === undefined && pathUnder(target, root) === undefined) links.push({ name, target });
}
return links;
}