Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
// Privacy invariants: the helper model is unset by default, never replaces an engine that can write the job itself, and
// never writes for a bot whose own engine is disallowed or whose helperModel switch is anything but absent or true.
import { randomUUID } from "node:crypto";
import { z } from "zod";
import { helperModelAllowed } from "../shared/wire.ts";
import type { MemoryModelFailure, MemoryModelOutcome, MemoryModelRun, MemoryModelSelection, MemoryModelStatus } from "../shared/memory-model.ts";
import { ChatCompletionError, ChatHttpError } from "./drivers/openai-chat-refusals.ts";
import { openRouterModelUnavailable } from "./drivers/openrouter-free.ts";
import { backgroundTextSlots, type JobSlots } from "./job-slots.ts";
import type { ModelSelection, ProviderAdapter, ProviderInstance, SmallModelFallback, TextGenerationOptions } from "./contracts.ts";
import { refusesModel } from "./quick-model-fallback.ts";
import type { LightModel, LightModelEngine } from "./suggested-reply/light-model.ts";
import { fastModelFor } from "./turn-route.ts";
import type { UsageRow, UsageTrigger } from "./usage-ledger.ts";
/** config.json `helper`: a connected instance and optionally one of its models. Stored config only, so a settings
* request cannot set it; a mistyped entry reads as no helper rather than costing the whole config. */
export const helperStoredShape = {
helper: z.object({
instanceId: z.string().trim().max(200).optional(),
model: z.string().trim().max(500).optional(),
}).optional().catch(undefined),
};
export interface HelperConfig {
helper?: { instanceId?: string; model?: string };
}
/** Goes into a CLI's argv: never a leading dash, no space or control character. */
export const ONE_OFF_MODEL_ID = /^[A-Za-z0-9][\x21-\x7e]*$/;
/** OMB_HELPER_INSTANCE / OMB_HELPER_MODEL win over the file; an empty OMB_HELPER_INSTANCE switches a saved helper off.
* An invalid model switches the helper off rather than writing with a model the person did not name. */
export function helperSelection(cfg: HelperConfig, env: Record<string, string | undefined> = process.env): { instanceId: string; model?: string } | null {
const instanceId = (env.OMB_HELPER_INSTANCE ?? cfg.helper?.instanceId)?.trim();
if (!instanceId) return null;
const model = (env.OMB_HELPER_MODEL ?? cfg.helper?.model)?.trim();
if (!model) return { instanceId };
return ONE_OFF_MODEL_ID.test(model) ? { instanceId, model } : null;
}
/** "representative": a person's assistant answering a teammate's question for them, which must never get tools. */
/** "suggested-reply": the composer's next-line suggestion, only ever on the bot's own engine's smallest model. */
export type SideJob = "compaction" | "memory" | "skill-review" | "setup-suggestions" | "representative" | "status-reply" | "skill-burger" | "suggested-reply" | "thread-title";
export type SideJobInstance = Pick<ProviderInstance, "instanceId" | "driverKind" | "enabled" | "generateText" | "generateMemoryText" | "models" | "quickModelsUsable" | "openRouter"> & {
adapter: { capabilities: Pick<ProviderAdapter["capabilities"], "agentsMcp"> };
};
export interface SideJobBot {
id: string;
name: string;
/** Where a spend alert a call raises is shown. */
threadId: string;
modelSelection: { instanceId: string; model?: string };
memoryModel?: MemoryModelSelection;
helperModel?: boolean;
}
export interface SideJobText {
via: "engine" | "helper";
memoryModel?: MemoryModelStatus;
generateText: (prompt: string, options?: SideJobTextOptions) => Promise<string>;
}
/** `waiting`: the call has to wait for a free slot (other bots' background calls); `started`: it starts now, after waiting
* or at once. A call that is never queued calls neither. */
export type SideJobTextOptions = Pick<TextGenerationOptions, "signal" | "timeoutMs" | "maxOutputTokens" | "finalTextOnly"> & {
waiting?(): void;
started?(): void;
onMemoryModel?(result: MemoryModelRun): void;
};
export interface SideJobsDeps {
bot: (botId: string) => SideJobBot | null | undefined;
instance: (instanceId: string) => SideJobInstance | null | undefined;
refusal: (instance: SideJobInstance) => string | undefined;
helper: () => { instanceId: string; model?: string } | null;
/** Small models each engine instance refused, kept across restarts. */
smallModels: { refused(instanceId: string): ReadonlySet<string>; remember(instanceId: string, model: string): void };
/** Hosted workspaces only. */
modelAllowed?: (selection: { instanceId: string; model: string }) => boolean;
assertWithinBudget: (botId?: string) => void;
book: (row: Omit<UsageRow, "at" | "costSource">, tokensReported: boolean, notificationThreadId: string) => void;
log?: (line: string) => void;
/** How many background jobs run at once, across bots. */
slots?: JobSlots;
/** The smallest model of an engine a suggested reply may run on; without it, or when it answers null, there is none. */
lightModel?: (engine: LightModelEngine, refused: ReadonlySet<string>) => LightModel | null;
}
interface SideJobContext {
threadId?: string;
instance?: SideJobInstance | null;
modelSelection?: SideJobBot["modelSelection"];
titleModel?: Pick<ModelSelection, "instanceId" | "model"> | null;
ownOnly?: boolean;
}
export interface SideJobs {
/** Null when nobody can write it. `at.instance` and `at.modelSelection` identify the conversation's engine and model. */
text(job: SideJob, botId: string, at?: SideJobContext): SideJobText | null;
}
type TextCall = (prompt: string, options?: TextGenerationOptions) => Promise<string>;
/** Jobs someone is waiting on, and the representative, which must never get tools, run only on a one-off text call:
* generateMemoryText starts a whole agent process. */
const ONE_OFF_ONLY: ReadonlySet<SideJob> = new Set(["compaction", "setup-suggestions", "representative", "status-reply", "skill-burger", "thread-title"]);
function ownCall(job: SideJob, instance: SideJobInstance): TextCall | undefined {
const call = ONE_OFF_ONLY.has(job) ? instance.generateText : instance.generateText ?? instance.generateMemoryText;
return call?.bind(instance);
}
/** A turn or a person is waiting on these, or the caller already holds a slot. */
const NEVER_QUEUED: ReadonlySet<SideJob> = new Set(["compaction", "representative", "status-reply", "thread-title"]);
/** A person sees these soon (a new bot's suggestions card): they wait ahead of memory upkeep and skill review. */
const SEEN_SOON: ReadonlySet<SideJob> = new Set(["setup-suggestions", "skill-burger", "suggested-reply"]);
function memoryModelFailure(error: unknown): MemoryModelFailure {
if (error instanceof DOMException && error.name === "TimeoutError") return "timeout";
if (error instanceof Error && "code" in error && error.code === "spend_cap") return "budget";
if (error instanceof ChatHttpError || error instanceof ChatCompletionError) {
switch (error.status) {
case 401: return "authentication";
case 402: return "credits";
case 403: return "forbidden";
case 408: return "timeout";
case 429: return "rateLimit";
}
}
return "request";
}
export function createSideJobs(deps: SideJobsDeps): SideJobs {
// Logged once per change, not once per call.
let said: string | null = null;
const say = (line: string | null) => {
if (line && line !== said) deps.log?.(`helper model: ${line}`);
said = line;
};
const ownFallback = (bot: SideJobBot, instance: SideJobInstance): SmallModelFallback => ({
...(bot.modelSelection.instanceId === instance.instanceId && bot.modelSelection.model ? { model: bot.modelSelection.model } : {}),
refused: deps.smallModels.refused(instance.instanceId),
onRefused: (model) => {
deps.log?.(`small model ${model} refused on ${instance.instanceId}: background text runs on the bot's own model`);
deps.smallModels.remember(instance.instanceId, model);
},
});
/** The engine's fastest model by the quick-turn rule. Not for Claude: its one-off call already runs its own small model,
* without thinking. */
const quickModel = (bot: SideJobBot, own: SideJobInstance): { model?: string } => {
if (own.driverKind === "claudeAgent" || own.quickModelsUsable?.() === false) return {};
const current = bot.modelSelection.instanceId === own.instanceId && bot.modelSelection.model ? bot.modelSelection.model : own.models.default;
const model = fastModelFor(own.models, current, deps.smallModels.refused(own.instanceId));
return model && (!deps.modelAllowed || deps.modelAllowed({ instanceId: own.instanceId, model })) ? { model } : {};
};
/** A refused quick model is remembered, so the next card skips it; there is no time left to retry this one. */
const rememberRefusal = (write: SideJobText["generateText"], own: SideJobInstance, model: string): SideJobText["generateText"] =>
async (prompt, options) => {
try {
return await write(prompt, options);
} catch (error) {
if (refusesModel(error instanceof Error ? error.message : String(error), model)) deps.smallModels.remember(own.instanceId, model);
throw error;
}
};
/** Every call checks the spend limit: one upkeep pass makes several in a row. */
const booked = (job: SideJob, bot: SideJobBot, instance: SideJobInstance, call: TextCall, trigger: UsageTrigger, fixed: () => TextGenerationOptions): SideJobText["generateText"] =>
async (prompt, options) => {
const { checkModel, ...generation } = fixed();
const budgetBot = job === "thread-title" ? bot.id : undefined;
if (!checkModel) deps.assertWithinBudget(budgetBot);
const threadId = job === "thread-title" ? bot.threadId : `${job}-${randomUUID()}`;
return call(prompt, {
...options,
...generation,
// The thread a title is for also fills a server's {threadId} request header.
...(job === "thread-title" ? { finalTextOnly: true, threadId: bot.threadId } : {}),
...(checkModel ? { checkModel: (model: string) => {
checkModel(model);
deps.assertWithinBudget(budgetBot);
} } : {}),
onUsage: (usage) => {
deps.book({
botId: bot.id,
botName: bot.name,
threadId,
instanceId: instance.instanceId,
driverKind: instance.driverKind,
model: usage.model,
input: usage.input ?? 0,
output: usage.output ?? 0,
...(usage.cachedInput !== undefined ? { cachedInput: usage.cachedInput } : {}),
costUsd: usage.costUsd ?? null,
trigger,
}, usage.input !== undefined && usage.output !== undefined, bot.threadId);
generation.onUsage?.(usage);
},
});
};
/** Pinned to the light model: its refusal fails the call rather than running on the bot's own model. */
const lightText = (bot: SideJobBot, own: SideJobInstance): SideJobText | null => {
const refused = deps.smallModels.refused(own.instanceId);
const light = deps.lightModel?.(own, refused);
if (!light || (deps.modelAllowed && !deps.modelAllowed({ instanceId: own.instanceId, model: light.model }))) return null;
const call = (light.call === "text" ? own.generateText : own.generateMemoryText)?.bind(own);
if (!call) return null;
const pinned: TextGenerationOptions = { model: light.model, fallback: { model: light.model, refused, onRefused: (model) => deps.smallModels.remember(own.instanceId, model) } };
return { via: "engine", generateText: rememberRefusal(booked("suggested-reply", bot, own, call, { kind: "bot", botId: bot.id }, () => pinned), own, light.model) };
};
const writeMemory = (bot: SideJobBot, own: SideJobInstance, call: TextCall, selected: MemoryModelSelection): SideJobText["generateText"] =>
async (prompt, { onMemoryModel, ...options } = {}) => {
const report = (result: MemoryModelOutcome) => onMemoryModel?.({ ...selected, ...result });
const allowed = (model: string) => deps.modelAllowed?.({ instanceId: own.instanceId, model }) !== false;
const stillSelected = () => {
const current = deps.bot(bot.id);
return current?.modelSelection.instanceId === own.instanceId && current.memoryModel?.instanceId === own.instanceId &&
current.memoryModel.model === selected.model && deps.instance(own.instanceId) === own && !deps.refusal(own);
};
const trigger: UsageTrigger = { kind: "bot", botId: bot.id };
options.signal?.throwIfAborted();
if (!stillSelected()) throw new Error("The memory model selection changed.");
if (!allowed(selected.model)) {
report({ state: "failed", reason: "forbidden" });
throw new Error("The memory model is not assigned to this workspace.");
}
try {
const answer = await booked("memory", bot, own, call, trigger, () => ({ model: selected.model }))(prompt, options);
if (!options.signal?.aborted) report({ state: "selected" });
return answer;
} catch (error) {
options.signal?.throwIfAborted();
if (!openRouterModelUnavailable(error, selected.model)) {
report({ state: "failed", reason: memoryModelFailure(error) });
throw error;
}
let used: string | undefined;
try {
const answer = await booked("memory", bot, own, call, trigger, () => ({
checkModel: (model) => {
if (!stillSelected() || !model || model === selected.model || !allowed(model)) throw error;
used = model;
},
onUsage: (usage) => { used = usage.model; },
}))(prompt, options);
if (!options.signal?.aborted && used) report({ state: "fallback", used });
return answer;
} catch (fallbackError) {
if (!options.signal?.aborted) report({ state: "failed", reason: fallbackError === error ? "unavailable" : memoryModelFailure(fallbackError) });
throw fallbackError;
}
}
};
/** Whatever the lookup throws reads as no helper: a helper never fails a job or the turn waiting on one. */
function usableHelper(): { instance: SideJobInstance; call: TextCall; model?: string } | null {
try {
return findHelper();
} catch (error) {
// A JSON error can quote the text it failed on.
const why = error instanceof SyntaxError ? "invalid JSON" : error instanceof Error ? error.message : "unknown";
say(`the helper could not be looked up (${why}), so bots whose engine has no one-off text call keep their fallback`);
return null;
}
}
function findHelper(): { instance: SideJobInstance; call: TextCall; model?: string } | null {
const helper = deps.helper();
if (!helper) {
say(null);
return null;
}
const name = JSON.stringify(helper.instanceId);
const unused = (why: string) => {
say(`${why}, so bots whose engine has no one-off text call keep their fallback`);
return null;
};
const instance = deps.instance(helper.instanceId);
if (!instance) return unused(`the helper instance ${name} is not connected`);
if (!instance.enabled) return unused(`the helper instance ${name} is switched off`);
if (!instance.generateText) return unused(`the helper instance ${name} cannot make a one-off text call`);
const refusal = deps.refusal(instance);
if (refusal) return unused(`the helper instance ${name} is not used (${refusal})`);
if (helper.model && deps.modelAllowed && !deps.modelAllowed({ instanceId: helper.instanceId, model: helper.model })) {
return unused(`the helper model ${JSON.stringify(helper.model)} is not assigned to this workspace`);
}
say(`small writing jobs for bots whose engine has no one-off text call are written by ${name}${helper.model ? ` (${helper.model})` : ""}`);
return { instance, call: instance.generateText.bind(instance), ...(helper.model ? { model: helper.model } : {}) };
}
const slots = deps.slots ?? backgroundTextSlots;
const queued = (job: SideJob, found: SideJobText | null): SideJobText | null => found && !NEVER_QUEUED.has(job)
? { ...found, generateText: (prompt, { waiting, started, ...options } = {}) => slots.run(() => {
started?.();
return found.generateText(prompt, options);
}, { signal: options.signal, interactive: SEEN_SOON.has(job), onWait: waiting }) }
: found;
function find(job: SideJob, botId: string, at: SideJobContext): SideJobText | null {
const record = deps.bot(botId);
if (!record) return null;
const bot = at.threadId ? { ...record, threadId: at.threadId } : record;
const selection = (job === "thread-title" ? at.modelSelection : undefined) ?? bot.modelSelection;
const own = at.instance ?? deps.instance(selection.instanceId);
if (!own || deps.refusal(own)) return null;
const ownTitleModel = selection.instanceId === own.instanceId ? selection.model : undefined;
if (job === "thread-title") {
if (!own.enabled || (deps.modelAllowed && (!ownTitleModel || !deps.modelAllowed({ instanceId: own.instanceId, model: ownTitleModel })))) return null;
if (at.titleModel && !at.ownOnly) {
const { instanceId, model } = at.titleModel;
const target = deps.instance(instanceId);
if (!target?.enabled || !target.generateText || deps.refusal(target) || deps.modelAllowed?.(at.titleModel) === false) return null;
const option = target.models.options.find(({ id }) => id === model);
if (option?.orgBlocked || option?.needsCliUpdate) return null;
return { via: "engine", generateText: booked(job, bot, target, target.generateText.bind(target), { kind: "bot", botId: bot.id }, () => ({ model })) };
}
if (own.driverKind === "claudeAgent" && ownTitleModel && !ONE_OFF_MODEL_ID.test(ownTitleModel)) return null;
}
if (job === "suggested-reply") return lightText(bot, own);
const selectedMemory = job === "memory" && bot.memoryModel?.instanceId === own.instanceId ? bot.memoryModel : undefined;
if (selectedMemory && (!own.openRouter || !own.enabled || !own.generateText)) return null;
// The review's changes are written with the bot's own skill tools, whoever read the conversation.
if (job === "skill-review" && own.adapter.capabilities.agentsMcp !== true) return null;
const call = ownCall(job, own);
if (call) {
// The summary belongs to a turn that already passed the spend limit and is not booked on its own.
if (job === "compaction") return { via: "engine", generateText: call };
if (job === "setup-suggestions") {
const quick = quickModel(bot, own);
const write = booked(job, bot, own, call, { kind: "bot", botId: bot.id }, () => ({ fallback: ownFallback(bot, own), ...quick }));
return { via: "engine", generateText: quick.model ? rememberRefusal(write, own, quick.model) : write };
}
if (job === "memory" && own.openRouter && own.enabled && own.generateText) {
return {
via: "engine",
memoryModel: selectedMemory ?? { instanceId: own.instanceId },
generateText: selectedMemory ? writeMemory(bot, own, call, selectedMemory) : booked(job, bot, own, call, { kind: "bot", botId: bot.id }, () => ({})),
};
}
return { via: "engine", generateText: booked(job, bot, own, call, { kind: "bot", botId: bot.id }, () => job === "thread-title" ? { model: ownTitleModel } : { fallback: ownFallback(bot, own) }) };
}
if (at.ownOnly || !helperModelAllowed(bot)) return null;
const helper = usableHelper();
if (!helper) return null;
const model = helper.model ?? (job === "thread-title" && deps.modelAllowed ? helper.instance.models.default : undefined);
if (job === "thread-title" && deps.modelAllowed && (!model || !deps.modelAllowed({ instanceId: helper.instance.instanceId, model }))) return null;
return { via: "helper", generateText: booked(job, bot, helper.instance, helper.call, { kind: "helper", botId: bot.id, job }, () => (model ? { model } : {})) };
}
return {
text: (job, botId, at = {}) => queued(job, find(job, botId, at)),
};
}