Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
// Security: local browse only, with no registry and no network fetch, so an import is exactly the bytes pasted here.
import { Search, X } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { intlLocale, t } from "@/lib/i18n";
import { useModalDialog } from "@/hooks/use-modal-dialog";
import { useAdvancedMode } from "@/lib/interface-mode";
import { useStore } from "@/state/store";
import { Card, Switch } from "./SettingsPrimitives";
import type { SkillsLibrarySkillWire } from "../../shared/wire";
import { Layer } from "./Layer";
import { Select } from "./Select";
import { serverFetch } from "@/lib/relay-server";
import { SKILL_FILE_ACCEPT, skillFilesOf } from "@/lib/skill-files";
export function filterLibrarySkills(
skills: readonly SkillsLibrarySkillWire[],
query: string,
tag: string | null,
): SkillsLibrarySkillWire[] {
const q = query.trim().toLowerCase();
return skills.filter((skill) => {
if (tag && !skill.tags.includes(tag)) return false;
if (!q) return true;
return [skill.name, skill.description, skill.source].some((part) => part.toLowerCase().includes(q));
});
}
export function LibrarySkillMeta({ skill }: { skill: SkillsLibrarySkillWire }) {
return (
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-ink-secondary">
<span className="truncate" title={skill.source}>{t("skills.source", { source: skill.source })}</span>
<span>{skill.version ? t("skills.library.version", { version: skill.version }) : t("skills.library.noVersion")}</span>
<span>{t("skills.library.importedAt", { date: new Date(skill.importedAt).toLocaleDateString(intlLocale()) })}</span>
{skill.tags.map((tag) => (
<span key={tag} className="rounded bg-control px-1.5 py-0.5 font-mono">{tag}</span>
))}
</div>
);
}
export function SkillsSection() {
const { state } = useStore();
const [skills, setSkills] = useState<SkillsLibrarySkillWire[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [query, setQuery] = useState("");
const [activeTag, setActiveTag] = useState<string | null>(null);
const [viewing, setViewing] = useState<{ skill: SkillsLibrarySkillWire; text: string; review: boolean } | null>(null);
const [working, setWorking] = useState("");
const [importText, setImportText] = useState("");
const [importing, setImporting] = useState(false);
const [importMessage, setImportMessage] = useState("");
const [assignBot, setAssignBot] = useState("");
const busy = useRef(false);
const fileInput = useRef<HTMLInputElement>(null);
const advanced = useAdvancedMode();
const bots = state.bots.filter((bot) => !bot.hidden);
const tags = useMemo(
() => [...new Set(skills.flatMap((skill) => skill.tags))].sort((a, b) => a.localeCompare(b)),
[skills],
);
const visible = filterLibrarySkills(skills, query, activeTag);
const refresh = async (cancelled?: () => boolean) => {
try {
const response = await serverFetch("/api/skills-library");
const body = (await response.json()) as { skills?: SkillsLibrarySkillWire[]; error?: string };
if (!response.ok) throw new Error(body.error ?? t("skills.library.loadError"));
if (cancelled?.()) return;
setSkills(body.skills ?? []);
setError("");
} catch (cause) {
if (!cancelled?.()) setError(cause instanceof Error ? cause.message : t("skills.library.loadError"));
} finally {
if (!cancelled?.()) setLoading(false);
}
};
useEffect(() => {
let cancelled = false;
setLoading(true);
void refresh(() => cancelled);
return () => {
cancelled = true;
};
}, []);
const putAssignments = async (botId: string, name: string, remove: boolean) => {
if (busy.current) return;
busy.current = true;
const label = `${name}:${botId}`;
setWorking(label);
setError("");
try {
// Read the complete current list while mutations are serialized, so a second row never overwrites an earlier
// assignment.
const listing = await serverFetch("/api/skills-library");
const listed = (await listing.json()) as { skills?: SkillsLibrarySkillWire[]; error?: string };
if (!listing.ok) throw new Error(listed.error ?? t("skills.library.loadError"));
const current = (listed.skills ?? []).filter((skill) => skill.assignedBots.some((bot) => bot.id === botId)).map((skill) => skill.name);
const next = remove ? current.filter((skill) => skill !== name) : [...new Set([...current, name])];
const response = await serverFetch(`/api/bots/${encodeURIComponent(botId)}/skills-library`, {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ skills: next }),
});
const body = (await response.json()) as { error?: string };
if (!response.ok) throw new Error(body.error ?? t("skills.error.assignments"));
await refresh();
} catch (cause) {
setError(cause instanceof Error ? cause.message : t("skills.error.assignments"));
} finally {
busy.current = false;
setWorking("");
}
};
const assign = async (skill: SkillsLibrarySkillWire) => {
if (!assignBot) return;
await putAssignments(assignBot, skill.name, false);
};
const unassign = async (skill: SkillsLibrarySkillWire, botId: string) => {
await putAssignments(botId, skill.name, true);
};
const toggle = async (skill: SkillsLibrarySkillWire, reviewed = false) => {
if (busy.current) return;
if (!skill.enabled && !reviewed) return view(skill, true);
busy.current = true;
setWorking(skill.name);
setError("");
try {
const response = await serverFetch(`/api/skills-library/${encodeURIComponent(skill.name)}`, {
method: "PATCH",
headers: { "content-type": "application/json" },
body: JSON.stringify({ enabled: !skill.enabled }),
});
const body = (await response.json()) as { error?: string };
if (!response.ok) throw new Error(body.error ?? t("skills.error.update"));
if (reviewed) setViewing(null);
await refresh();
} catch (cause) {
setError(cause instanceof Error ? cause.message : t("skills.error.update"));
} finally {
busy.current = false;
setWorking("");
}
};
const toggleEveryBot = async (skill: SkillsLibrarySkillWire) => {
if (busy.current) return;
busy.current = true;
setWorking(skill.name);
setError("");
try {
const response = await serverFetch(`/api/skills-library/${encodeURIComponent(skill.name)}`, {
method: "PATCH",
headers: { "content-type": "application/json" },
body: JSON.stringify({ everyBot: !skill.everyBot }),
});
const body = (await response.json()) as { error?: string };
if (!response.ok) throw new Error(body.error ?? "Could not update this skill.");
await refresh();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Could not update this skill.");
} finally {
busy.current = false;
setWorking("");
}
};
const view = async (skill: SkillsLibrarySkillWire, review = false) => {
setError("");
try {
const response = await serverFetch(`/api/skills-library/${encodeURIComponent(skill.name)}`);
const body = (await response.json()) as { text?: string; error?: string };
if (!response.ok) throw new Error(body.error ?? t("skills.error.load"));
if (!body.text) throw new Error(t("skills.error.contentsImport"));
setViewing({ skill, text: body.text, review });
} catch (cause) {
setError(cause instanceof Error ? cause.message : t("skills.error.load"));
}
};
const importOne = async (text: string): Promise<string> => {
const response = await serverFetch("/api/skills-library", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ text }),
});
const body = (await response.json()) as { skill?: { name: string }; error?: string };
if (!response.ok) throw new Error(body.error ?? t("skills.error.import"));
return body.skill?.name ?? "";
};
const importSkill = async () => {
const text = importText.trim();
if (!text) return;
setImporting(true);
setError("");
setImportMessage("");
try {
const name = await importOne(text);
setImportMessage(t("skills.library.imported", { name }));
setImportText("");
await refresh();
} catch (cause) {
setError(cause instanceof Error ? cause.message : t("skills.error.import"));
} finally {
setImporting(false);
}
};
/** Each chosen SKILL.md goes through the same local import as a paste: no URL is read, and the bytes are the file's. */
const importFiles = async (list: FileList | null) => {
const files = skillFilesOf(list);
if (!files.length) return;
setImporting(true);
setError("");
setImportMessage("");
const failed: Array<{ name: string; reason: string }> = [];
let imported = 0;
try {
for (const file of files) {
try {
await importOne((await file.text()).trim());
imported++;
} catch (cause) {
failed.push({ name: file.name, reason: cause instanceof Error ? cause.message : t("skills.error.import") });
}
}
if (imported) {
setImportMessage(imported === 1 ? t("skills.library.importFileDone") : t("skills.library.importFilesDone", { count: imported }));
await refresh();
}
if (failed.length) {
const named = failed.slice(0, 3).map((file) => `${file.name} (${file.reason})`).join(", ") + (failed.length > 3 ? "…" : "");
setError(failed.length === 1 ? t("skills.library.importFileFailed", { names: named }) : t("skills.library.importFilesFailed", { count: failed.length, names: named }));
}
} finally {
setImporting(false);
if (fileInput.current) fileInput.current.value = "";
}
};
const inputClass =
"w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[14px] text-ink placeholder:text-ink-secondary focus:outline-none";
return (
<div className="flex flex-col gap-4">
<Card title={t("skills.library.title")} subtitle={t("skills.library.subtitle")}>
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<Search size={15} className="shrink-0 text-ink-secondary" />
<input
className={inputClass}
placeholder={t("skills.library.searchPlaceholder")}
aria-label={t("skills.library.searchPlaceholder")}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
</div>
{tags.length > 0 && (
<div className="flex flex-wrap items-center gap-1.5">
<button
type="button"
onClick={() => setActiveTag(null)}
className={
activeTag === null
? "rounded-full bg-control px-2.5 py-1 text-[12px] font-medium text-ink"
: "rounded-full px-2.5 py-1 text-[12px] text-ink-secondary hover:bg-control/50 hover:text-ink"
}
>
{t("skills.library.allTags")}
</button>
{tags.map((tag) => (
<button
key={tag}
type="button"
onClick={() => setActiveTag(activeTag === tag ? null : tag)}
className={
activeTag === tag
? "rounded-full bg-control px-2.5 py-1 font-mono text-[12px] font-medium text-ink"
: "rounded-full px-2.5 py-1 font-mono text-[12px] text-ink-secondary hover:bg-control/50 hover:text-ink"
}
>
{tag}
</button>
))}
</div>
)}
{loading ? (
<div className="text-[12px] text-ink-secondary">{t("skills.library.loading")}</div>
) : visible.length === 0 ? (
<div className="rounded-lg bg-inset px-3 py-2 text-[12px] text-ink-secondary">
{skills.length === 0 ? t("skills.library.empty") : t("skills.library.noMatches")}
</div>
) : (
<div className="divide-y divide-hairline/40 overflow-hidden rounded-lg border border-hairline/40">
{visible.map((skill) => (
<div key={skill.name} className="px-3 py-2.5">
<div className="flex items-center gap-2">
<button type="button" onClick={() => void view(skill)} className="min-w-0 flex-1 text-left" aria-label={t("skills.library.view", { skill: skill.name })}>
<div className="truncate font-mono text-[13px] text-ink">{skill.name}</div>
<div className="mt-0.5 line-clamp-2 text-[12px] text-ink-secondary">{skill.description}</div>
</button>
<Switch
checked={skill.enabled}
aria-label={skill.enabled ? t("skills.library.disable", { skill: skill.name }) : t("skills.library.enable", { skill: skill.name })}
disabled={Boolean(working || importing)}
onClick={() => void toggle(skill)}
/>
</div>
<LibrarySkillMeta skill={skill} />
<div className="mt-2 flex items-center justify-between gap-3 rounded-lg bg-inset px-2.5 py-2">
<div>
<div className="text-[12px] font-medium text-ink">{t("skills.library.everyBot")}</div>
<div className="text-[11px] text-ink-secondary">{t("skills.library.everyBotHint")}</div>
</div>
<Switch
checked={skill.everyBot}
aria-label={t("skills.library.everyBot")}
disabled={Boolean(working || importing)}
onClick={() => void toggleEveryBot(skill)}
/>
</div>
{skill.warnings.length > 0 && (
<div className="mt-1 text-[11px] text-warning">{skill.warnings.join(" · ")}</div>
)}
<div className="mt-1.5 flex flex-wrap items-center gap-1.5 text-[11px] text-ink-secondary">
{skill.assignedBots.length === 0 ? (
<span>{t("skills.library.notAssigned")}</span>
) : (
skill.assignedBots.map((bot) => (
<span key={bot.id} className="flex items-center gap-1 rounded-full bg-control px-2 py-0.5">
<span className="max-w-40 truncate">{bot.name}</span>
<button
type="button"
aria-label={t("skills.library.removeAssignment", { bot: bot.name })}
title={t("skills.library.removeAssignment", { bot: bot.name })}
disabled={Boolean(working || importing)}
onClick={() => void unassign(skill, bot.id)}
className="flex size-4 items-center justify-center rounded-full text-ink-secondary hover:bg-danger/10 hover:text-danger disabled:opacity-40"
>
<X size={11} />
</button>
</span>
))
)}
</div>
{bots.length > 0 && (
<div className="mt-1.5 flex items-center gap-1.5">
<Select
size="sm"
aria-label={t("skills.library.assignLabel")}
value={assignBot}
disabled={Boolean(working || importing)}
onChange={(e) => setAssignBot(e.target.value)}
className="max-w-45"
>
<option value="">{t("skills.library.assignPickBot")}</option>
{bots.map((bot) => (
<option key={bot.id} value={bot.id}>{bot.name}</option>
))}
</Select>
<button
type="button"
disabled={!assignBot || Boolean(working || importing)}
onClick={() => void assign(skill)}
className="rounded-lg bg-control px-2.5 py-1 text-[12px] text-ink hover:bg-raised-hover disabled:opacity-50"
>
{t("skills.library.assign")}
</button>
</div>
)}
</div>
))}
</div>
)}
{error && <div role="alert" className="mt-2 text-[12px] text-danger">{error}</div>}
</div>
</Card>
<Card title={t("skills.library.importTitle")} subtitle={t("skills.library.importHint")}>
<form
className="flex flex-col gap-2"
onSubmit={(e) => {
e.preventDefault();
void importSkill();
}}
>
<textarea
className={`${inputClass} min-h-32 font-mono text-[12px]`}
placeholder={t("skills.library.importPlaceholder")}
aria-label={t("skills.library.importTitle")}
value={importText}
onChange={(e) => setImportText(e.target.value)}
/>
<div className="flex items-center justify-between gap-2">
{importMessage ? <div className="text-[12px] text-ink-secondary">{importMessage}</div> : <span />}
<div className="flex shrink-0 items-center gap-2">
{advanced && <input
ref={fileInput}
type="file"
accept={SKILL_FILE_ACCEPT}
multiple
className="hidden"
aria-hidden="true"
tabIndex={-1}
onChange={(e) => void importFiles(e.target.files)}
/>}
{advanced && <button type="button" onClick={() => fileInput.current?.click()} disabled={importing || Boolean(working)} className="ui-button ui-button-md">
{t("skills.library.importFiles")}
</button>}
<button
type="submit"
disabled={importing || Boolean(working) || !importText.trim()}
className="rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50"
>
{importing ? t("skills.library.importing") : t("skills.library.importButton")}
</button>
</div>
</div>
</form>
</Card>
{viewing && <Layer modal><SkillSourceDialog viewing={viewing} error={error} working={Boolean(working)} onClose={() => { if (!working) setViewing(null); }} onEnable={() => void toggle(viewing.skill, true)} /></Layer>}
</div>
);
}
function SkillSourceDialog({ viewing, error, working, onClose, onEnable }: {
viewing: { skill: SkillsLibrarySkillWire; text: string; review: boolean };
error: string;
working: boolean;
onClose: () => void;
onEnable: () => void;
}) {
const dialogRef = useRef<HTMLDivElement>(null);
useModalDialog(dialogRef, onClose);
return (
<div
ref={dialogRef}
tabIndex={-1}
role="dialog"
aria-modal="true"
aria-labelledby="skills-library-view-title"
className="fixed inset-0 z-[90] flex items-center justify-center bg-black/45 p-6"
>
<div className="flex max-h-[min(760px,90vh)] w-full max-w-2xl flex-col rounded-2xl bg-card p-5 shadow-2xl">
<div className="flex items-center justify-between gap-3">
<div id="skills-library-view-title" className="text-[16px] font-semibold text-ink">{viewing.review ? t("skills.reviewTitle", { name: viewing.skill.name }) : viewing.skill.name}</div>
<button
type="button"
disabled={working}
onClick={onClose}
className="rounded-md px-2 py-1 text-[13px] text-ink-secondary hover:bg-control hover:text-ink"
>
{t("skills.library.close")}
</button>
</div>
{viewing.review && <LibrarySkillMeta skill={viewing.skill} />}
{viewing.skill.warnings.length > 0 && <div className="mt-2 text-[12px] text-warning">{viewing.skill.warnings.join(" · ")}</div>}
<pre
tabIndex={0}
aria-label={`${t("skills.library.view", { skill: viewing.skill.name })}`}
className="mt-3 min-h-0 flex-1 overflow-auto whitespace-pre-wrap break-words rounded-xl bg-inset p-3 font-mono text-[12px] leading-relaxed text-ink"
>
{viewing.text}
</pre>
{error && <div role="alert" className="mt-2 text-[12px] text-danger">{error}</div>}
{viewing.review && <button type="button" disabled={working} onClick={onEnable} className="mt-4 self-end rounded-lg bg-accent px-4 py-2 text-[13px] font-semibold text-white disabled:opacity-40">{t("skills.enableReviewed")}</button>}
</div>
</div>
);
}