Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Revert #4984 from the train: meetbot.ts is copied to the computer as one file and sits at its 1,047-line pin; the fix adds 90 lines
milind-soni03baa8b1c7bb
diff --git a/server/meetings/meetbot.test.ts b/server/meetings/meetbot.test.tsindex 1585772d33..b728d46ad3 100644--- a/server/meetings/meetbot.test.ts+++ b/server/meetings/meetbot.test.ts@@ -1,8 +1,5 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";import { describe, expect, it, vi } from "vitest";-import { ADAPTERS, attribute, chunkStream, noteQuestion, runSession, teamsSafeName, whisperStream, type CallPage, type MeetbotConfig, type SessionParts } from "./meetbot.ts";+import { ADAPTERS, attribute, chunkStream, noteQuestion, runSession, teamsSafeName, type CallPage, type MeetbotConfig, type SessionParts } from "./meetbot.ts";const config: MeetbotConfig = {url: "https://meet.systemli.org/room", platform: "jitsi", name: "Ada (notes)", consent: "Hi, I'm Ada (notes). Ask me with @notes.",@@ -155,82 +152,6 @@ describe("the meeting bot on Google Meet", () => {});});-describe("local transcription install", () => {- function scriptedSpawn(plan: Array<number | "hang">) {- const calls: Array<{ file: string; args: string[]; detached?: boolean }> = [];- const killed: string[] = [];- const groups: number[] = [];- let n = 0;- const spawn = ((file: string, args: readonly string[] = [], options?: { detached?: boolean }) => {- const behavior = plan[n++] ?? "hang";- calls.push({ file, args: [...args], detached: options?.detached });- const listeners: Array<(code: number | null) => void> = [];- const child = {- pid: 424242,- kill(signal?: string) {- killed.push(signal ?? "SIGTERM");- for (const listener of listeners) listener(null);- },- on(event: string, cb: (code: number | null) => void) {- if (event === "exit") {- listeners.push(cb);- if (typeof behavior === "number") queueMicrotask(() => cb(behavior));- }- return child;- },- stdout: null,- stdin: null,- };- return child;- }) as unknown as typeof import("node:child_process").spawn;- return { spawn, calls, killed, groups };- }-- it("leaves while the first install is still running", async () => {- const home = mkdtempSync(join(tmpdir(), "omb-whisper-"));- const events: Array<{ type: string; data?: Record<string, unknown> }> = [];- const scripted = scriptedSpawn(["hang"]);- const stream = whisperStream((type, data) => { events.push({ type, data }); }, () => {}, () => {}, {- home,- stopWaitMs: 50,- groupProcesses: true,- killGroup(pid: number) { scripted.groups.push(pid); },- spawn: scripted.spawn,- });- const result = await Promise.race([- stream.stop().then(() => "stopped"),- new Promise((resolve) => setTimeout(() => resolve("hung"), 1_000)),- ]);- rmSync(home, { recursive: true, force: true });- expect(result).toBe("stopped");- expect(scripted.killed).toContain("SIGKILL");- expect(scripted.groups).toEqual([424242]);- expect(scripted.calls[0]?.detached).toBe(true);- expect(events.some((event) => event.type === "stt" && event.data?.status === "installing")).toBe(true);- expect(events.some((event) => event.type === "stt" && event.data?.status === "failed")).toBe(false);- });-- it("installs again when the virtual environment cannot import", async () => {- const home = mkdtempSync(join(tmpdir(), "omb-whisper-"));- mkdirSync(join(home, "venv", "bin"), { recursive: true });- writeFileSync(join(home, "venv", "bin", "python"), "");- const events: Array<{ type: string; data?: Record<string, unknown> }> = [];- const scripted = scriptedSpawn([1, "hang"]);- const stream = whisperStream((type, data) => { events.push({ type, data }); }, () => {}, () => {}, {- home,- stopWaitMs: 50,- spawn: scripted.spawn,- });- for (let i = 0; i < 50 && scripted.calls.length < 2; i++) await new Promise((resolve) => setTimeout(resolve, 10));- await stream.stop();- rmSync(home, { recursive: true, force: true });- expect(scripted.calls[0]?.args).toEqual(["-c", "import faster_whisper, numpy"]);- expect(scripted.calls[1]?.file).toBe("bash");- expect(events.some((event) => event.type === "stt" && event.data?.status === "installing")).toBe(true);- expect(events.some((event) => event.type === "stt" && event.data?.status === "failed")).toBe(false);- });-});-describe("speech-to-text done by the server", () => {it("sends each utterance, cut on silence, as an audio event and attributes the words that come back", async () => {const events: Array<{ type: string; data?: Record<string, any> }> = [];diff --git a/server/meetings/meetbot.ts b/server/meetings/meetbot.tsindex 92fc22b37a..9969659534 100644--- a/server/meetings/meetbot.ts+++ b/server/meetings/meetbot.ts@@ -43,31 +43,6 @@ export type EndReason = "left" | "stop_requested" | "meeting_ended" | "removed"const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));-/** A pip install on a dead network, or ffmpeg on a stuck pipe, never exits. Leave must not wait for that. */-const WHISPER_INSTALL_MS = 10 * 60_000;-const WHISPER_PROBE_MS = 15_000;-const STOP_INSTALL_WAIT_MS = 1_000;-const FFMPEG_ENCODE_MS = 20_000;--function boundChild(child: ChildProcess, timeoutMs: number, end: () => void): Promise<void> {- return new Promise((resolve, reject) => {- let settled = false;- const finish = (error?: Error) => {- if (settled) return;- settled = true;- clearTimeout(timer);- if (error) reject(error);- else resolve();- };- const timer = setTimeout(() => {- end();- finish(new Error(`timed out after ${timeoutMs} ms`));- }, timeoutMs);- child.on("error", (error) => finish(error));- child.on("exit", (code) => finish(code === 0 ? undefined : new Error(`exited ${code}`)));- });-}-export function eventLog(dir: string) {const file = join(dir, "events.jsonl");let seq = existsSync(file) ? readFileSync(file, "utf8").split("\n").filter(Boolean).length : 0;@@ -814,64 +789,23 @@ for chunk in iter(lambda: sys.stdin.buffer.read(FRAME * 4), b""):`;/** Speech-to-text on the computer itself, for a person with no speech key: faster-whisper, installed on first use. */-export function whisperStream(emit: SessionParts["emit"], onWords: (words: Word[]) => void, log: (line: string) => void,- options: { home?: string; spawn?: typeof spawn; installMs?: number; stopWaitMs?: number; groupProcesses?: boolean; killGroup?: (pid: number) => void } = {}) {- const home = options.home ?? join(process.env.HOME ?? "/tmp", ".mausbot-meet");- const run = options.spawn ?? spawn;+function whisperStream(emit: SessionParts["emit"], onWords: (words: Word[]) => void, log: (line: string) => void) {+ const home = join(process.env.HOME ?? "/tmp", ".mausbot-meet");const python = join(home, "venv", "bin", "python");- // `python3 -m venv` stays a child of Bash. A Linux process group lets leave kill both.- const groupProcesses = options.groupProcesses ?? process.platform !== "win32";- const killGroup = options.killGroup ?? ((pid: number) => { process.kill(-pid, "SIGKILL"); });- const endChild = (child: ChildProcess, group: boolean) => {- if (group && typeof child.pid === "number" && child.pid > 0) {- try { killGroup(child.pid); } catch { /* already gone */ }- }- try { child.kill("SIGKILL"); } catch { /* already gone */ }- };mkdirSync(home, { recursive: true });writeFileSync(join(home, "whisper_worker.py"), WHISPER_WORKER);let worker: ChildProcess | null = null;- let install: ChildProcess | null = null;- let endInstall: (() => void) | null = null;- let stopped = false;let startedAt = 0;const queue: Buffer[] = [];- const watchInstall = async (child: ChildProcess, timeoutMs: number, group: boolean) => {- const end = () => endChild(child, group);- install = child;- endInstall = end;- try {- await boundChild(child, timeoutMs, end);- } finally {- if (install === child) {- install = null;- endInstall = null;- }- }- };const ready = (async () => {- let depsReady = false;- if (existsSync(python)) {- try {- await watchInstall(run(python, ["-c", "import faster_whisper, numpy"], { stdio: "ignore" }), WHISPER_PROBE_MS, false);- depsReady = !stopped;- } catch {- depsReady = false;- }- }- if (stopped) return;- if (!depsReady) {+ if (!existsSync(python)) {emit("stt", { status: "installing" });- const script = `python3 -m venv ${JSON.stringify(join(home, "venv"))} && ${JSON.stringify(join(home, "venv", "bin", "pip"))} install -q faster-whisper numpy`;- try {- await watchInstall(run("bash", ["-c", script], { stdio: "ignore", detached: groupProcesses }), options.installMs ?? WHISPER_INSTALL_MS, groupProcesses);- } catch (error) {- if (stopped) return;- throw error;- }+ await new Promise<void>((resolve, reject) => {+ const install = spawn("bash", ["-c", `python3 -m venv ${JSON.stringify(join(home, "venv"))} && ${JSON.stringify(join(home, "venv", "bin", "pip"))} install -q faster-whisper numpy`], { stdio: "ignore" });+ install.on("exit", (code) => (code === 0 ? resolve() : reject(new Error(`installing local speech-to-text failed (${code})`))));+ });}- if (stopped) return;- worker = run(python, [join(home, "whisper_worker.py")], { stdio: ["pipe", "pipe", "ignore"] });+ worker = spawn(python, [join(home, "whisper_worker.py")], { stdio: ["pipe", "pipe", "ignore"] });let pending = "";worker.stdout!.on("data", (data) => {pending += data;@@ -887,10 +821,7 @@ export function whisperStream(emit: SessionParts["emit"], onWords: (words: Word[});emit("stt", { status: "connected" });for (const chunk of queue.splice(0)) worker.stdin!.write(chunk);- })().catch((error: Error) => {- if (stopped) return;- emit("stt", { status: "failed", detail: error.message });- });+ })().catch((error: Error) => emit("stt", { status: "failed", detail: error.message }));return {write(chunk: Buffer) {if (!startedAt) startedAt = Date.now() - chunk.length / 32;@@ -898,18 +829,10 @@ export function whisperStream(emit: SessionParts["emit"], onWords: (words: Word[else if (queue.length < 4_000) queue.push(chunk);},async stop() {- stopped = true;- endInstall?.();- await new Promise<void>((resolve) => {- let settled = false;- const finish = () => { if (settled) return; settled = true; clearTimeout(timer); resolve(); };- const timer = setTimeout(finish, options.stopWaitMs ?? STOP_INSTALL_WAIT_MS);- ready.catch(() => {}).then(finish);- });- if (!worker) return;- worker.stdin?.end();+ await ready;+ worker?.stdin?.end();await sleep(4_000);- worker.kill();+ worker?.kill();},};}@@ -984,22 +907,9 @@ function encodeOpus(pcm: Buffer): Promise<Buffer> {return new Promise((resolve, reject) => {const ffmpeg = spawn("ffmpeg", ["-loglevel", "error", "-f", "s16le", "-ar", "16000", "-ac", "1", "-i", "-", "-c:a", "libopus", "-b:a", "32k", "-f", "ogg", "-"], { stdio: ["pipe", "pipe", "ignore"] });const out: Buffer[] = [];- let settled = false;- let timer: ReturnType<typeof setTimeout>;- const finish = (error: Error | null, audio?: Buffer) => {- if (settled) return;- settled = true;- clearTimeout(timer);- if (error) reject(error);- else resolve(audio ?? Buffer.concat(out));- };- timer = setTimeout(() => {- ffmpeg.kill("SIGKILL");- finish(new Error("ffmpeg timed out"));- }, FFMPEG_ENCODE_MS);ffmpeg.stdout!.on("data", (data: Buffer) => out.push(data));- ffmpeg.on("error", (error) => finish(error));- ffmpeg.on("close", (code) => finish(code === 0 ? null : new Error(`ffmpeg exited ${code}`)));+ ffmpeg.on("error", reject);+ ffmpeg.on("close", (code) => (code === 0 ? resolve(Buffer.concat(out)) : reject(new Error(`ffmpeg exited ${code}`))));ffmpeg.stdin!.end(pcm);});}