Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

6.3 KB
Raw Blame
// The engine homes of a Team Cloud at run time. A turn's spawns run inside its conversation (`within`, set around each
// adapter's sendTurn and keep-warm ping), and procs.ts asks `forSpawn` for the home of that conversation's audience. Off a
// Team Cloud nothing is started and every spawn keeps the server's HOME.
import { AsyncLocalStorage } from "node:async_hooks";
import { mkdirSync } from "node:fs";
import { homedir } from "node:os";
import { join, relative } from "node:path";

import type { Audience } from "../audience.ts";
import type { ProviderInstance } from "../contracts.ts";
import { audienceHome, audienceHomeKey, audienceHomes, homedSpawn, type HomedSpawn } from "./layout.ts";
import { migrateEngineHomes, type MigrationResult, type MigrationThread } from "./migrate.ts";
import { syncSignIns } from "./sign-ins.ts";

export interface EngineHomesSetup {
  dataDir: string;
  serverHome?: string;
  audienceOf(threadId: string): Audience;
  /** Every conversation the server resumes, for the first start's move. */
  threads(): Iterable<MigrationThread>;
  env?: Record<string, string | undefined>;
  log?: (line: string) => void;
}

export class EngineHomes {
  #setup: (EngineHomesSetup & { serverHome: string }) | null = null;
  #migration: MigrationResult | null = null;
  readonly #thread = new AsyncLocalStorage<string>();
  readonly #bot = new AsyncLocalStorage<string | undefined>();

  start(setup: EngineHomesSetup): void {
    this.#setup = { ...setup, serverHome: setup.serverHome ?? homedir() };
    this.#migration = null;
  }

  stop(): void {
    this.#setup = null;
  }

  active(): boolean {
    return this.#setup !== null;
  }

  /** Runs `start` with what it spawns counted as this conversation's (and its bot's, when the caller names it). */
  within<T>(threadId: string, start: () => T, botId?: string): T {
    return this.#setup ? this.#thread.run(threadId, () => this.#bot.run(botId, start)) : start();
  }

  /** The conversation the caller runs in, on a Team Cloud; undefined elsewhere. */
  thread(): string | undefined {
    return this.#setup ? this.#thread.getStore() : undefined;
  }

  /** The bot whose turn the caller runs in, on a Team Cloud, when its adapter was told. */
  bot(): string | undefined {
    return this.#setup ? this.#bot.getStore() : undefined;
  }

  /** The audience key of the conversation the caller runs in, so engines never share a process across audiences. */
  scope(): string | null {
    const threadId = this.#setup ? this.#thread.getStore() : undefined;
    return threadId === undefined ? null : audienceHomeKey(this.#setup!.audienceOf(threadId));
  }

  /** The first spawn after a start moves what the engines kept in the server's HOME (migrate.ts). */
  migrate(): MigrationResult | null {
    const setup = this.#setup;
    if (!setup) return null;
    if (this.#migration) return this.#migration;
    try {
      this.#migration = migrateEngineHomes({ dataDir: setup.dataDir, serverHome: setup.serverHome, env: setup.env ?? process.env, threads: setup.threads, audienceOf: setup.audienceOf });
      if (this.#migration.ran || this.#migration.swept) {
        (setup.log ?? console.log)(`engine homes: moved ${this.#migration.moved} session files to their conversations, held ${this.#migration.held}, deleted ${this.#migration.swept} held folders past their time`);
      }
    } catch (error) {
      this.#migration = { ran: false, moved: 0, held: 0, swept: 0 };
      (setup.log ?? console.warn)(`engine homes: the move from the server's home failed: ${error instanceof Error ? error.message : String(error)}`);
    }
    return this.#migration;
  }

  /** The environment as an engine sees it from each place it can run: the server's HOME, and on a Team Cloud every
   * audience's home too. */
  everyHome(env: Record<string, string | undefined>): Array<Record<string, string | undefined>> {
    const setup = this.#setup;
    if (!setup) return [env];
    return [env, ...audienceHomes(setup.dataDir).map((home) => homedSpawn(env, { dataDir: setup.dataDir, serverHome: setup.serverHome, home }).env)];
  }

  /** On a Team Cloud, inside a conversation: the spawn with HOME and the engines' folders in its audience's home, the
   * home made, and the team's sign-ins in it. Null otherwise. */
  forSpawn(env: Record<string, string | undefined>): HomedSpawn | null {
    const setup = this.#setup;
    const threadId = setup ? this.#thread.getStore() : undefined;
    if (!setup || threadId === undefined) return null;
    this.migrate();
    const home = audienceHome(setup.dataDir, setup.audienceOf(threadId));
    mkdirSync(home, { recursive: true, mode: 0o700 });
    const homed = homedSpawn(env, { dataDir: setup.dataDir, serverHome: setup.serverHome, home });
    for (const folder of homed.folders) mkdirSync(folder, { recursive: true, mode: 0o700 });
    const others = audienceHomes(setup.dataDir).filter((dir) => dir !== home);
    syncSignIns(homed.shared, (target) => others.map((dir) => join(dir, relative(home, target))));
    return homed;
  }
}

export const engineHomes = new EngineHomes();

/** On a Team Cloud, every turn, keep-warm ping and warm summary of this instance runs inside its conversation. */
export function withEngineHomes(instance: ProviderInstance, homes: EngineHomes = engineHomes): ProviderInstance {
  if (!homes.active()) return instance;
  const adapter = instance.adapter;
  const warm = adapter.cacheKeepWarm;
  (instance as { adapter: ProviderInstance["adapter"] }).adapter = {
    ...adapter,
    sendTurn: (input) => homes.within(input.threadId, () => adapter.sendTurn(input), input.botId),
    ...(adapter.compactSession ? { compactSession: (threadId, options) => homes.within(threadId, () => adapter.compactSession!(threadId, options), options.botId) } : {}),
    ...(adapter.prestart ? { prestart: { ...adapter.prestart, start: (input, waitMs) => homes.within(input.threadId, () => adapter.prestart!.start(input, waitMs), input.botId) } } : {}),
    ...(warm ? { cacheKeepWarm: {
      ...warm,
      ping: (threadId, options) => homes.within(threadId, () => warm.ping(threadId, options)),
      // A summary forks the conversation's session, which lives in its audience's home, and starts the bot's servers there.
      ...(warm.compact ? { compact: (threadId, options) => homes.within(threadId, () => warm.compact!(threadId, options)) } : {}),
    } } : {}),
  };
  return instance;
}