Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
import { appendFileSync, existsSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { removeTempDir } from "./testing/cleanup.ts";
import {
appendUsage,
flushUsageLedger,
parseUsageRange,
readUsage,
summarizeUsage,
triggerKey,
triggerLabel,
usageCsv,
usageFileFor,
usageLedgerParses,
USAGE_GROUPINGS,
type UsageRow,
} from "./usage-ledger.ts";
import { summarizeInsights } from "./usage-insights.ts";
function row(overrides: Partial<UsageRow> = {}): Omit<UsageRow, "at"> & { at?: string } {
return {
botId: "b1",
botName: "Scout",
threadId: "t1",
instanceId: "claude",
driverKind: "claudeAgent",
model: "claude-sonnet-5",
input: 1200,
output: 300,
cachedInput: 900,
costUsd: 0.012,
trigger: { kind: "user", email: "[email protected]", label: "Ada's laptop" },
...overrides,
};
}
describe("usage ledger files", () => {
let dataDir: string;
beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), "omb-usage-")); });
afterEach(async () => { await removeTempDir(dataDir); });
it("appends one private row per turn into the month's file and reads it back in order", async () => {
appendUsage(dataDir, row({ at: "2026-09-03T10:00:00.000Z" }));
appendUsage(dataDir, row({ at: "2026-09-03T11:00:00.000Z", botId: "b2", botName: "Clerk", costUsd: null }));
appendUsage(dataDir, row({ at: "2026-10-01T00:00:00.000Z", botId: "b3", botName: "Later" }));
await flushUsageLedger(dataDir);
const september = usageFileFor(dataDir, new Date("2026-09-15T00:00:00Z"));
expect(september.endsWith(join("usage", "2026-09.jsonl"))).toBe(true);
expect(readFileSync(september, "utf8").trim().split("\n")).toHaveLength(2);
if (process.platform !== "win32") {
expect(statSync(september).mode & 0o777).toBe(0o600);
expect(statSync(join(dataDir, "usage")).mode & 0o777).toBe(0o700);
}
const rows = readUsage(dataDir, { from: new Date("2026-09-01T00:00:00Z"), to: new Date("2026-10-31T23:59:59Z") });
expect(rows.map((r) => r.botId)).toEqual(["b1", "b2", "b3"]);
expect(rows[1]!.costUsd).toBeNull();
expect(rows[0]!.costSource).toBe("reported");
expect(rows[1]).not.toHaveProperty("costSource");
});
it("carries the prompt byte split when present and drops malformed values", async () => {
appendUsage(dataDir, row({ at: "2026-09-03T10:00:00.000Z", promptBytes: { stable: 21_396, volatile: 8_102 } }));
appendUsage(dataDir, row({ at: "2026-09-03T11:00:00.000Z", promptBytes: { stable: -4, volatile: "big" } as unknown as { stable: number; volatile: number } }));
await flushUsageLedger(dataDir);
const rows = readUsage(dataDir, { from: new Date("2026-09-01T00:00:00Z"), to: new Date("2026-09-30T23:59:59Z") });
expect(rows[0]!.promptBytes).toEqual({ stable: 21_396, volatile: 8_102 });
expect(rows[1]).not.toHaveProperty("promptBytes");
});
it("stores an estimate as such, and drops a label that has no cost behind it", async () => {
appendUsage(dataDir, row({ at: "2026-09-03T10:00:00.000Z", costUsd: 0.25, costSource: "estimated" }));
appendUsage(dataDir, row({ at: "2026-09-03T11:00:00.000Z", costUsd: null, costSource: "estimated" }));
await flushUsageLedger(dataDir);
const rows = readUsage(dataDir, { from: new Date("2026-09-01T00:00:00Z"), to: new Date("2026-09-30T23:59:59Z") });
expect(rows[0]).toMatchObject({ costUsd: 0.25, costSource: "estimated" });
expect(rows[1]!.costUsd).toBeNull();
expect(rows[1]).not.toHaveProperty("costSource");
});
it("filters by time, skips torn lines and foreign rows, and never stores a negative or fractional token", async () => {
appendUsage(dataDir, row({ at: "2026-09-03T10:00:00.000Z", input: -5, output: 12.7, cachedInput: Number.NaN, costUsd: -1 }));
await flushUsageLedger(dataDir);
const file = usageFileFor(dataDir, new Date("2026-09-03T00:00:00Z"));
writeFileSync(file, readFileSync(file, "utf8") + '{"at":"2026-09-04T00:00:00.000Z","botId":"x"' + "\n" + JSON.stringify({ unrelated: true }) + "\n", { flag: "w" });
const rows = readUsage(dataDir, { from: new Date("2026-09-01T00:00:00Z"), to: new Date("2026-09-30T23:59:59Z") });
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({ input: 0, output: 12, cachedInput: 0, costUsd: null });
expect(readUsage(dataDir, { from: new Date("2026-09-04T00:00:00Z"), to: new Date("2026-09-30T23:59:59Z") })).toHaveLength(0);
});
it("keeps a full disk or a missing directory from failing the turn", async () => {
appendUsage(join(dataDir, "missing-file-as-dir"), row());
writeFileSync(join(dataDir, "blocked"), "not a directory");
appendUsage(join(dataDir, "blocked"), row());
await expect(flushUsageLedger(join(dataDir, "blocked"))).resolves.toBeUndefined();
expect(existsSync(join(dataDir, "blocked", "usage"))).toBe(false);
});
});
describe("usage ledger reads", () => {
let dataDir: string;
beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), "omb-usage-")); });
afterEach(async () => { await removeTempDir(dataDir); });
const september = { from: new Date("2026-09-01T00:00:00Z"), to: new Date("2026-09-30T23:59:59Z") };
const both = { from: new Date("2026-09-01T00:00:00Z"), to: new Date("2026-10-31T23:59:59Z") };
const file = () => usageFileFor(dataDir, new Date("2026-09-15T00:00:00Z"));
/** The rows a plain parse of the files gives, with no memory of an earlier read. */
const parsedAfresh = (range: { from: Date; to: Date }): UsageRow[] => ["2026-09", "2026-10"].flatMap((month) => {
const path = join(dataDir, "usage", `${month}.jsonl`);
if (!existsSync(path)) return [];
return readFileSync(path, "utf8").split("\n").flatMap((line) => {
try {
const value = JSON.parse(line) as UsageRow;
const at = Date.parse(value.at);
return typeof value.botId === "string" && at >= range.from.getTime() && at <= range.to.getTime() ? [value] : [];
} catch { return []; }
});
});
const seed = async () => {
appendUsage(dataDir, row({ at: "2026-09-03T10:00:00.000Z" }));
appendUsage(dataDir, row({ at: "2026-09-20T11:00:00.000Z", botId: "b2", botName: "Clerk", costUsd: null }));
appendUsage(dataDir, row({ at: "2026-10-01T00:00:00.000Z", botId: "b3", botName: "Later" }));
await flushUsageLedger(dataDir);
};
const parsesDuring = (run: () => void) => { const before = usageLedgerParses(); run(); return usageLedgerParses() - before; };
it("parses a month file once, and answers every later read and range from it with the same rows", async () => {
await seed();
let first: UsageRow[] = [];
expect(parsesDuring(() => { first = readUsage(dataDir, both); })).toBe(2);
expect(first).toEqual(parsedAfresh(both));
expect(parsesDuring(() => {
expect(readUsage(dataDir, both)).toEqual(first);
expect(readUsage(dataDir, september)).toEqual(parsedAfresh(september));
const late = { from: new Date("2026-09-10T00:00:00Z"), to: new Date("2026-09-30T23:59:59Z") };
expect(readUsage(dataDir, late).map((r) => r.botId)).toEqual(["b2"]);
expect(readUsage(dataDir, late)).toEqual(parsedAfresh(late));
})).toBe(0);
});
it("reads again after the server's own append", async () => {
await seed();
readUsage(dataDir, september);
appendUsage(dataDir, row({ at: "2026-09-21T00:00:00.000Z", botId: "b4" }));
await flushUsageLedger(dataDir);
let rows: UsageRow[] = [];
expect(parsesDuring(() => { rows = readUsage(dataDir, september); })).toBe(1);
expect(rows.map((r) => r.botId)).toEqual(["b1", "b2", "b4"]);
expect(rows).toEqual(parsedAfresh(september));
});
it("reads again when anything else changed the file: more bytes, a new time, another file in its place, or none", async () => {
await seed();
readUsage(dataDir, september);
appendFileSync(file(), JSON.stringify({ ...row({ botId: "b5" }), at: "2026-09-22T00:00:00.000Z" }) + "\n");
expect(readUsage(dataDir, september).map((r) => r.botId)).toEqual(["b1", "b2", "b5"]);
utimesSync(file(), new Date("2026-09-25T00:00:00Z"), new Date("2026-09-25T00:00:00Z"));
expect(parsesDuring(() => readUsage(dataDir, september))).toBe(1);
const replacement = `${file()}.next`;
writeFileSync(replacement, readFileSync(file(), "utf8").replaceAll('"botId":"b5"', '"botId":"b6"'));
utimesSync(replacement, statSync(file()).atime, statSync(file()).mtime);
renameSync(replacement, file());
expect(readUsage(dataDir, september).map((r) => r.botId)).toEqual(["b1", "b2", "b6"]);
rmSync(file());
expect(readUsage(dataDir, september)).toEqual([]);
expect(readUsage(dataDir, both).map((r) => r.botId)).toEqual(["b3"]);
});
it("hands every reader the same row objects, which no summary changes", async () => {
await seed();
const frozen = <T>(value: T): T => {
if (value && typeof value === "object") { Object.freeze(value); Object.values(value).forEach(frozen); }
return value;
};
const rows = frozen(readUsage(dataDir, both));
const before = JSON.stringify(rows);
for (const groupBy of USAGE_GROUPINGS) summarizeUsage(rows, groupBy, null, groupBy === "model" ? null : "model");
usageCsv(rows);
summarizeInsights(rows, { from: "2026-09-01", to: "2026-10-31" }, "UTC");
expect(JSON.stringify(readUsage(dataDir, both))).toBe(before);
});
});
describe("usage ranges", () => {
const now = new Date("2026-09-15T12:00:00Z");
it("defaults to the month to date and accepts inclusive day bounds", () => {
expect(parseUsageRange(undefined, undefined, now)).toEqual({ from: new Date("2026-09-01T00:00:00Z"), to: now });
const range = parseUsageRange("2026-08-01", "2026-08-31", now)!;
expect(range.from.toISOString()).toBe("2026-08-01T00:00:00.000Z");
expect(range.to.toISOString()).toBe("2026-08-31T23:59:59.999Z");
});
it("rejects malformed, impossible, reversed, or year-long ranges", () => {
expect(parseUsageRange("2026-8-1", undefined, now)).toBeNull();
expect(parseUsageRange("2026-02-31", undefined, now)).toBeNull();
expect(parseUsageRange("2026-09-10", "2026-09-01", now)).toBeNull();
expect(parseUsageRange("2025-01-01", "2026-09-01", now)).toBeNull();
expect(parseUsageRange("2025-09-10", "2026-09-10", now)).not.toBeNull();
});
});
describe("usage summaries", () => {
const rows: UsageRow[] = [
{ ...row({ at: "2026-09-01T10:00:00.000Z" }), at: "2026-09-01T10:00:00.000Z" } as UsageRow,
{ ...row({ at: "2026-09-01T11:00:00.000Z", botId: "b2", botName: "Clerk", model: "gpt-5", driverKind: "codex", costUsd: null, trigger: { kind: "owner" } }), at: "2026-09-01T11:00:00.000Z" } as UsageRow,
{ ...row({ at: "2026-09-02T09:00:00.000Z", input: 100, output: 50, cachedInput: 0, costUsd: 0.5, trigger: { kind: "routine", routineId: "r1", label: "Morning digest" } }), at: "2026-09-02T09:00:00.000Z" } as UsageRow,
{ ...row({ at: "2026-09-02T10:00:00.000Z", botId: "b2", botName: "Clerk", costUsd: 0.001, trigger: { kind: "bot", botId: "b1" } }), at: "2026-09-02T10:00:00.000Z" } as UsageRow,
];
it("groups by bot, money first, and counts unpriced rows instead of hiding them", () => {
const summary = summarizeUsage(rows, "bot");
expect(summary.groups.map((g) => [g.label, g.turns, g.costUsd, g.unpriced])).toEqual([
["Scout", 2, 0.512, 0],
["Clerk", 2, 0.001, 1],
]);
expect(summary.total).toMatchObject({ turns: 4, input: 1200 + 1200 + 100 + 1200, output: 300 + 300 + 50 + 300, cachedInput: 900 * 3, unpriced: 1 });
expect(summary.total.costUsd).toBeCloseTo(0.513, 6);
});
it("groups by person with stable keys, by model, by engine, and by day in date order", () => {
expect(summarizeUsage(rows, "user").groups.map((g) => [g.key, g.label])).toEqual([
["routine:r1", "Routine: Morning digest"],
["user:[email protected]", "[email protected]"],
["bot", "Bot to bot"],
["owner", "This computer"],
]);
expect(summarizeUsage(rows, "model").groups.map((g) => g.key)).toEqual(["model:claudeAgent/claude-sonnet-5", "model:codex/gpt-5"]);
expect(summarizeUsage(rows, "engine").groups.map((g) => g.label)).toEqual(["claudeAgent", "codex"]);
expect(summarizeUsage(rows, "day").groups.map((g) => [g.label, g.turns])).toEqual([["2026-09-01", 2], ["2026-09-02", 2]]);
expect(summarizeUsage([], "day")).toEqual({ groups: [], total: expect.objectContaining({ turns: 0, costUsd: null }) });
});
it("splits any group by model, largest bar first, only when a different dimension is asked for", () => {
const mixed: UsageRow[] = [
rows[0]!,
{ ...rows[0]!, model: "gpt-6.1-sol", driverKind: "codex", instanceId: "codex", input: 100, output: 20, cachedInput: 0, costUsd: 0.001 },
rows[1]!,
];
const [scout, clerk] = summarizeUsage(mixed, "bot", null, "model").groups;
expect(scout!.segments?.map((piece) => [piece.key, piece.input, piece.output])).toEqual([
["model:claudeAgent/claude-sonnet-5", 1200, 300],
["model:codex/gpt-6.1-sol", 100, 20],
]);
expect(clerk!.segments?.map((piece) => piece.key)).toEqual(["model:codex/gpt-5"]);
expect(summarizeUsage(mixed, "bot").groups[0]!.segments).toBeUndefined();
expect(summarizeUsage(mixed, "model", null, "model").groups[0]!.segments).toBeUndefined();
expect(summarizeUsage(mixed, "day", null, "model").groups[0]!.segments?.map((piece) => piece.key)).toEqual([
"model:claudeAgent/claude-sonnet-5",
"model:codex/gpt-5",
"model:codex/gpt-6.1-sol",
]);
});
it("orders a group's segments by the fresh tokens its bar draws, not by cached input", () => {
const cached: UsageRow = {
...rows[0]!,
model: "claude-sonnet-5",
input: 10_000,
cachedInput: 9_800,
output: 100,
};
const fresh: UsageRow = {
...rows[0]!,
model: "gpt-6.1-sol",
driverKind: "codex",
instanceId: "codex",
input: 600,
output: 100,
cachedInput: 0,
};
expect(summarizeUsage([cached, fresh], "bot", null, "model").groups[0]!.segments?.map((piece) => piece.key)).toEqual([
"model:codex/gpt-6.1-sol",
"model:claudeAgent/claude-sonnet-5",
]);
});
it("keeps the bar total additive when one row's cached input exceeds its input", () => {
const uneven: UsageRow[] = [
{ ...row({ model: "claude-sonnet-5", input: 100, output: 10, cachedInput: 150 }), at: "2026-09-01T10:00:00.000Z" } as UsageRow,
{ ...row({ model: "gpt-6.1-sol", driverKind: "codex", instanceId: "codex", input: 500, output: 50, cachedInput: 100 }), at: "2026-09-01T11:00:00.000Z" } as UsageRow,
];
const [scout] = summarizeUsage(uneven, "bot", null, "model").groups;
const fresh = (entry: UsageRow) =>
Math.max(0, entry.input - Math.min(entry.cachedInput ?? 0, entry.input)) + entry.output;
const expected = uneven.reduce((sum, entry) => sum + fresh(entry), 0);
expect(scout!.barTokens).toBe(expected);
expect(scout!.segments!.reduce((sum, piece) => sum + (piece.barTokens ?? 0), 0)).toBe(expected);
expect(scout!.barTokens).toBe(460);
expect(scout!.input - Math.min(scout!.cachedInput, scout!.input) + scout!.output).toBe(410);
});
it("groups by routine, with every non-routine turn in one manual bucket", () => {
const summary = summarizeUsage(rows, "routine");
expect(summary.groups.map((g) => [g.key, g.label, g.turns, g.costUsd])).toEqual([
["routine:r1", "Morning digest", 1, 0.5],
["manual", "Not from a routine", 3, expect.closeTo(0.013, 6)],
]);
expect(summary.total.turns).toBe(4);
});
it("prices groups from the operator's list and adds a billable column to the CSV only then", () => {
const prices = { default: { inputPerMillion: 1000, outputPerMillion: 2000 }, "codex/gpt-5": { inputPerMillion: 0, outputPerMillion: 0 } };
const priced = summarizeUsage(rows, "bot", prices);
// Scout: one claude turn of 1200 in (900 cached at the input rate) / 300 out, one of 100 / 50
expect(priced.groups[0]!.billableUsd).toBeCloseTo((1200 * 1000 + 300 * 2000) / 1e6 + (100 * 1000 + 50 * 2000) / 1e6, 9);
// Clerk: one gpt-5 turn priced at zero, one claude turn at the default
expect(priced.groups[1]!.billableUsd).toBeCloseTo((1200 * 1000 + 300 * 2000) / 1e6, 9);
expect(priced.total.billableUsd).toBeCloseTo(priced.groups[0]!.billableUsd! + priced.groups[1]!.billableUsd!, 9);
expect(summarizeUsage(rows, "bot").total.billableUsd).toBeNull();
expect(usageCsv([rows[0]!], prices).split("\n")[0]).toContain(",cost_usd,cost_source,billable_usd,thread");
expect(usageCsv([rows[0]!], prices).split("\n")[1]).toContain(",0.012,reported,1.8,t1");
expect(usageCsv([rows[0]!]).split("\n")[0]).not.toContain("billable_usd");
});
it("groups by department as booked, and counts a routine's or a teammate's work for a person as theirs", () => {
const booked: UsageRow[] = [
{ ...rows[0]!, section: "Finance" },
{ ...rows[2]!, section: "Finance", trigger: { kind: "routine", routineId: "r1", label: "Morning digest", email: "[email protected]" } },
{ ...rows[3]!, trigger: { kind: "bot", botId: "b1", email: "[email protected]" } },
rows[1]!,
];
expect(summarizeUsage(booked, "department").groups.map((g) => [g.key, g.label, g.turns])).toEqual([
["department:Finance", "Finance", 2],
["department:", "", 2],
]);
expect(summarizeUsage(booked, "user").groups.map((g) => [g.key, g.turns])).toEqual([
["user:[email protected]", 2],
["user:[email protected]", 1],
["owner", 1],
]);
expect(summarizeUsage(booked, "routine").groups[0]).toMatchObject({ key: "routine:r1", turns: 1 });
expect(usageCsv([booked[1]!]).split("\n")[1]).toMatch(/,Finance,ada@example\.test$/);
});
it("names a person by email before device label and never throws on an empty trigger", () => {
expect(triggerLabel({ kind: "user", label: "Phone" })).toBe("Phone");
expect(triggerKey({ kind: "user", email: "[email protected]" })).toBe("user:[email protected]");
expect(triggerKey({ kind: "user" })).toBe("user:unknown");
expect(triggerLabel({ kind: "routine" })).toBe("Routine: unknown");
});
it("keeps helper-model calls in a group of their own, apart from bot-to-bot turns, and never as a routine", () => {
const helper: UsageRow = {
...row({ botId: "b2", botName: "Clerk", threadId: "memory-1", instanceId: "claude", driverKind: "claudeAgent", model: "claude-haiku-4-5", costUsd: 0.002, trigger: { kind: "helper", botId: "b2", job: "memory" } }),
at: "2026-09-02T11:00:00.000Z",
};
expect(triggerKey(helper.trigger)).toBe("helper");
expect(triggerLabel(helper.trigger)).toBe("Helper model");
const byPerson = summarizeUsage([...rows, helper], "user").groups;
expect(byPerson.find((group) => group.key === "helper")).toMatchObject({ label: "Helper model", turns: 1, costUsd: 0.002 });
expect(byPerson.find((group) => group.key === "bot")).toMatchObject({ label: "Bot to bot", turns: 1, costUsd: 0.001 });
// still the bot's spend, on the helper's engine, and not a routine's
expect(summarizeUsage([helper], "bot").groups.map((group) => group.label)).toEqual(["Clerk"]);
expect(summarizeUsage([helper], "engine").groups.map((group) => group.label)).toEqual(["claudeAgent"]);
expect(summarizeUsage([helper], "routine").groups.map((group) => group.key)).toEqual(["manual"]);
expect(usageCsv([helper]).split("\n")[1]).toBe("2026-09-02T11:00:00.000Z,Clerk,claude-haiku-4-5,claudeAgent,Helper model,1200,300,900,0.002,reported,memory-1,,");
});
it("exports spreadsheet-safe CSV with one line per turn", () => {
const csv = usageCsv([
rows[0]!,
{ ...rows[1]!, botName: '=HYPERLINK("x")', trigger: { kind: "user", email: "a,[email protected]" } },
]);
const lines = csv.trim().split("\n");
expect(lines[0]).toBe("time,bot,model,engine,triggered_by,input_tokens,output_tokens,cached_input_tokens,cost_usd,cost_source,thread,department,person");
expect(lines[1]).toBe("2026-09-01T10:00:00.000Z,Scout,claude-sonnet-5,claudeAgent,[email protected],1200,300,900,0.012,reported,t1,,[email protected]");
expect(lines[2]).toContain("\"'=HYPERLINK(\"\"x\"\")\"");
expect(lines[2]).toContain('"a,[email protected]"');
expect(lines[2]).toMatch(/,,,t1,,"a,b@example.test"$/);
expect(usageCsv([{ ...rows[0]!, costSource: "estimated" }]).split("\n")[1]).toContain(",0.012,estimated,t1");
});
it("keeps estimates apart from reported cost, and reads rows written before estimates existed as reported", () => {
const estimated = { ...rows[1]!, costUsd: 0.2, costSource: "estimated" as const };
const legacy = { ...rows[0]! }; // costUsd 0.012, no costSource
const summary = summarizeUsage([legacy, estimated, rows[2]!], "bot");
expect(summary.total.costUsd).toBeCloseTo(0.712, 9);
expect(summary.total.estimatedUsd).toBeCloseTo(0.2, 9);
expect(summary.total.unpriced).toBe(0);
const clerk = summary.groups.find((g) => g.label === "Clerk")!;
expect(clerk).toMatchObject({ costUsd: 0.2, estimatedUsd: 0.2 });
expect(summary.groups.find((g) => g.label === "Scout")!.estimatedUsd).toBeNull();
expect(summarizeUsage([rows[1]!], "bot").total).toMatchObject({ costUsd: null, estimatedUsd: null, unpriced: 1 });
});
});