Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Show spend by department, and count routine and delegated work toward the person (#4165)
Azad Jagtap2a8d4cb262b6
diff --git a/server/index.ts b/server/index.tsindex 0321a9e742..41c3813e5f 100644--- a/server/index.ts+++ b/server/index.ts@@ -185,7 +185,7 @@ import { startUpkeep } from "./host/start-upkeep.ts";import { ComputerControl } from "./computer-control.ts";import { resetPathCache } from "./env-path.ts";import { registerEnginesBinDir } from "./engine-install.ts";-import { appendUsage, flushUsageLedger, queuedTurnTrigger, usageTriggerFor, type UsageRow, type UsageTrigger } from "./usage-ledger.ts";+import { appendUsage, flushUsageLedger, queuedTurnTrigger, usageTriggerFor, type UsageRow, type UsageTrigger } from "./usage-ledger.ts"; import { createUsageAttribution } from "./usage-attribution.ts";import { createTraceRecorder } from "./usage-trace/recorder.ts";import { GroupUsageReader } from "./group-thread-usage.ts";import { ledgerCost } from "./model-prices.ts";@@ -1401,9 +1401,9 @@ function operatorPrices(): PriceList | null {return entitled("billing") && cfg.billing?.prices && Object.keys(cfg.billing.prices).length ? cfg.billing.prices : null;}-function bookTurnUsage(row: Omit<UsageRow, "at" | "costSource">, tokensReported = true, notificationThreadId = row.threadId): void {+const attributeUsage = createUsageAttribution({ section: (botId) => store.bot(botId)?.section, threadTrigger: (threadId) => turnTriggers.get(threadId), routineWriter: (id) => { const key = cloudRoutineAuthors?.writer(id); return key ? teamOwners.people?.list().find((one) => personKey({ id: "", email: one.email }) === key)?.email : undefined; } }); function bookTurnUsage(row: Omit<UsageRow, "at" | "costSource">, tokensReported = true, notificationThreadId = row.threadId): void {const cost = tokensReported || row.costUsd !== null ? ledgerCost(row, operatorPrices()) : { costUsd: null };- const booked = { ...row, ...cost, ...usageTrace.settle(row.threadId), at: new Date().toISOString() };+ const booked = attributeUsage({ ...row, ...cost, ...usageTrace.settle(row.threadId), at: new Date().toISOString() });// The append is async; noteSpend counts the row from memory until it lands, so the cap check sees it.noteSpend(DATA_DIR, booked, appendUsage(DATA_DIR, booked));const state = spendState(cfg, DATA_DIR);diff --git a/server/usage-attribution.e2e.test.ts b/server/usage-attribution.e2e.test.tsindex d0e9eca342..a51fb149d2 100644--- a/server/usage-attribution.e2e.test.ts+++ b/server/usage-attribution.e2e.test.ts@@ -154,6 +154,25 @@ posixOnly("usage attribution e2e", () => {await waitFor(async () => (await getBot(unlisted.id)).busy === false, "the bots to go idle");}, 40_000);+ it("books each turn to the department its bot was in then, and moving the bot later keeps what was spent there", async () => {+ const bot = await newBot("acpHappy", "grok-4.7");+ expect((await api("PATCH", `/api/bots/${bot.id}`, { section: "Finance" })).status).toBe(200);+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "for finance" })).status).toBe(202);+ await waitFor(() => ledger(bot.id).length === 1, "the Finance turn to be booked");+ await waitFor(async () => (await getBot(bot.id)).busy === false, "the bot to go idle");+ expect(ledger(bot.id)[0]).toMatchObject({ section: "Finance" });+ expect((await api("PATCH", `/api/bots/${bot.id}`, { section: "Operations" })).status).toBe(200);+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "for operations" })).status).toBe(202);+ await waitFor(() => ledger(bot.id).length === 2, "the Operations turn to be booked");+ await waitFor(async () => (await getBot(bot.id)).busy === false, "the bot to go idle");+ const byDepartment = (await api("GET", "/api/usage?groupBy=department")).body.groups as Array<{ key: string; turns: number }>;+ expect(byDepartment.find((group) => group.key === "department:Finance")).toMatchObject({ turns: 1 });+ expect(byDepartment.find((group) => group.key === "department:Operations")).toMatchObject({ turns: 1 });+ const csv = await (await fetch(`${BASE}/api/usage.csv`)).text();+ expect(csv.split("\n")[0]).toMatch(/,thread,department,person$/);+ expect(csv).toContain(",Finance,");+ }, 40_000);+it("a queued message leaves the running turn with its starter, and its own turn is booked to its sender", async () => {const bot = await newBot("acp", "fake-model");expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "owner's work" })).status).toBe(202);diff --git a/server/usage-attribution.test.ts b/server/usage-attribution.test.tsnew file mode 100644index 0000000000..8bb444fd6b--- /dev/null+++ b/server/usage-attribution.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from "vitest";+import { createUsageAttribution } from "./usage-attribution.ts";+import type { UsageTrigger } from "./usage-ledger.ts";++const ADA = "[email protected]";++function world(running: Record<string, UsageTrigger> = {}) {+ const sections: Record<string, string> = { payroll: "Finance", helpdesk: " " };+ return createUsageAttribution({ section: (botId) => sections[botId], routineWriter: (id) => (id === "digest" ? ADA : undefined), threadTrigger: (threadId) => running[threadId] });+}+const row = (botId: string, trigger: UsageTrigger, turnId?: string, parent?: string, parentThread = "t") =>+ ({ botId, trigger, ...(turnId ? { turnId } : {}), ...(parent ? { parent: { threadId: parentThread, turnId: parent } } : {}) });++describe("who and which department a usage row was spent for", () => {+ it("stamps the bot's department as it is when booked, and none for a blank one", () => {+ const attribute = world();+ expect(attribute(row("payroll", { kind: "owner" }))).toMatchObject({ section: "Finance" });+ expect(attribute(row("helpdesk", { kind: "owner" }))).not.toHaveProperty("section");+ });++ it("names a routine's writer, and leaves a routine nobody on the team wrote as it was", () => {+ const attribute = world();+ expect(attribute(row("payroll", { kind: "routine", routineId: "digest" })).trigger).toEqual({ kind: "routine", routineId: "digest", email: ADA });+ expect(attribute(row("payroll", { kind: "routine", routineId: "other" })).trigger).toEqual({ kind: "routine", routineId: "other" });+ });++ it("follows delegated work back to the person whose turn started it, through teammates of teammates", () => {+ const attribute = world();+ attribute(row("payroll", { kind: "user", email: ADA }, "turn-ada"));+ expect(attribute(row("helpdesk", { kind: "bot", botId: "payroll" }, "turn-helper", "turn-ada")).trigger).toEqual({ kind: "bot", botId: "payroll", email: ADA });+ expect(attribute(row("payroll", { kind: "bot", botId: "helpdesk" }, "turn-deeper", "turn-helper")).trigger).toMatchObject({ email: ADA });+ expect(attribute(row("payroll", { kind: "bot" }, "turn-orphan", "turn-unknown")).trigger).toEqual({ kind: "bot" });+ expect(attribute(row("payroll", { kind: "owner" }, "turn-owner")).trigger).toEqual({ kind: "owner" });+ });++ it("names the person while the delegating turn is still running, and books a room member's turn it handed work to as theirs", () => {+ const attribute = world({ "t-ada": { kind: "user", email: ADA } });+ expect(attribute(row("helpdesk", { kind: "bot", botId: "payroll" }, "turn-child", "turn-ada-running", "t-ada")).trigger).toEqual({ kind: "bot", botId: "payroll", email: ADA });+ expect(attribute(row("helpdesk", { kind: "owner" }, "turn-room", "turn-ada-running", "t-ada")).trigger).toEqual({ kind: "owner", email: ADA });+ expect(attribute(row("helpdesk", { kind: "owner" }, "turn-plain")).trigger).toEqual({ kind: "owner" });+ });+});diff --git a/server/usage-attribution.ts b/server/usage-attribution.tsnew file mode 100644index 0000000000..1fb9de25df--- /dev/null+++ b/server/usage-attribution.ts@@ -0,0 +1,46 @@+// Who a usage row was spent for, and in which department. A routine's row names the person who wrote the routine (on a+// Team Cloud), and work a teammate did for a delegating turn names the person whose turn started the job, followed+// down the trace's parent links; the department is the bot's when the row is booked, so moving a bot later never+// rewrites what was spent.+import type { UsageRow } from "./usage-ledger.ts";++const REMEMBERED_TURNS = 5_000;++export interface UsageAttributionDeps {+ /** The bot's department now; blank or missing is none. */+ section(botId: string): string | undefined;+ /** The email of the person who wrote the routine, when known. */+ routineWriter(routineId: string): string | undefined;+ /** What started the conversation's current turn: a parent still running has no row yet. */+ threadTrigger?(threadId: string): UsageRow["trigger"] | undefined;+}++export function createUsageAttribution(deps: UsageAttributionDeps) {+ const turnPerson = new Map<string, string>();+ const remember = (turnId: string | undefined, email: string | undefined) => {+ if (!turnId || !email) return;+ turnPerson.delete(turnId);+ turnPerson.set(turnId, email);+ if (turnPerson.size > REMEMBERED_TURNS) turnPerson.delete(turnPerson.keys().next().value!);+ };+ return <Row extends Pick<UsageRow, "botId" | "trigger" | "turnId" | "parent">>(row: Row): Row & Pick<UsageRow, "section"> => {+ const section = deps.section(row.botId)?.trim();+ let trigger = row.trigger;+ if (trigger.kind === "routine" && !trigger.email && trigger.routineId) {+ const email = deps.routineWriter(trigger.routineId);+ if (email) trigger = { ...trigger, email };+ } else if (trigger.kind !== "user" && trigger.kind !== "routine" && !trigger.email && row.parent) {+ // A teammate can finish before the turn that delegated to it is booked.+ const parentTrigger = deps.threadTrigger?.(row.parent.threadId);+ const email = turnPerson.get(row.parent.turnId) ?? (parentTrigger ? personOf(parentTrigger) : undefined);+ if (email) trigger = { ...trigger, email };+ }+ remember(row.turnId, personOf(trigger));+ return { ...row, trigger, ...(section ? { section } : {}) };+ };+}++/** The person a row was spent for, if any. */+export function personOf(trigger: UsageRow["trigger"]): string | undefined {+ return trigger.email;+}diff --git a/server/usage-ledger.test.ts b/server/usage-ledger.test.tsindex eba45639ee..783a835545 100644--- a/server/usage-ledger.test.ts+++ b/server/usage-ledger.test.ts@@ -169,6 +169,26 @@ describe("usage summaries", () => {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]");@@ -190,7 +210,7 @@ describe("usage summaries", () => {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");+ 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", () => {@@ -199,11 +219,11 @@ describe("usage summaries", () => {{ ...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");- expect(lines[1]).toBe("2026-09-01T10:00:00.000Z,Scout,claude-sonnet-5,claudeAgent,[email protected],1200,300,900,0.012,reported,t1");+ 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$/);+ expect(lines[2]).toMatch(/,,,t1,,"a,[email protected]"$/);expect(usageCsv([{ ...rows[0]!, costSource: "estimated" }]).split("\n")[1]).toContain(",0.012,estimated,t1");});diff --git a/server/usage-ledger.ts b/server/usage-ledger.tsindex e8e06b4add..65791aca57 100644--- a/server/usage-ledger.ts+++ b/server/usage-ledger.ts@@ -1,4 +1,5 @@// Append-only usage rows under <data>/usage/ (0600): bookkeeping never fails the turn, and rows never carry message text.+import { personOf } from "./usage-attribution.ts";import { readFileSync } from "node:fs";import { appendFile, mkdir } from "node:fs/promises";import { join } from "node:path";@@ -9,12 +10,14 @@ import { billableFor, type PriceList } from "./prices.ts";import type { RequestAuth } from "./request-auth.ts";/** `helper`: a job the helper model wrote for `botId`, kept apart from `bot` so its cost reads on its own. */+/** `email` on an owner, routine, bot or helper row: the person it was spent for (`usage-attribution.ts`), such as the+ * person whose turn delegated to it. */export type UsageTrigger =| { kind: "user"; email?: string; label?: string }- | { kind: "owner" }- | { kind: "routine"; routineId?: string; label?: string; runId?: string }- | { kind: "bot"; botId?: string }- | { kind: "helper"; botId?: string; job?: string };+ | { kind: "owner"; email?: string }+ | { kind: "routine"; routineId?: string; label?: string; runId?: string; email?: string }+ | { kind: "bot"; botId?: string; email?: string }+ | { kind: "helper"; botId?: string; job?: string; email?: string };export interface UsageRow {at: string;@@ -31,6 +34,8 @@ export interface UsageRow {costUsd: number | null;costSource?: CostSource;trigger: UsageTrigger;+ /** The bot's department when the row was booked. */+ section?: string;/** Trace fields, on rows booked since traces were recorded: older rows have none and show as untimed. */turnId?: string;startedAt?: string;@@ -48,8 +53,8 @@ export interface UsageRow {usageStatus?: TraceUsageStatus;}-export type UsageGroupBy = "bot" | "model" | "user" | "day" | "engine" | "routine";-export const USAGE_GROUPINGS: readonly UsageGroupBy[] = ["bot", "model", "user", "day", "engine", "routine"];+export type UsageGroupBy = "bot" | "model" | "user" | "day" | "engine" | "routine" | "department";+export const USAGE_GROUPINGS: readonly UsageGroupBy[] = ["bot", "model", "user", "day", "engine", "routine", "department"];export interface UsageGroup {key: string;@@ -248,14 +253,20 @@ function groupOf(row: UsageRow, groupBy: UsageGroupBy): { key: string; label: streturn { key: `bot:${row.botId}`, label: row.botName || row.botId };case "model":return { key: `model:${row.driverKind}/${row.model}`, label: row.model };- case "user":- return { key: triggerKey(row.trigger), label: triggerLabel(row.trigger) };+ case "user": {+ // A routine's or a teammate's work for a known person counts as theirs.+ const email = personOf(row.trigger);+ return email ? { key: `user:${email.toLowerCase()}`, label: email } : { key: triggerKey(row.trigger), label: triggerLabel(row.trigger) };+ }case "day":return { key: `day:${row.at.slice(0, 10)}`, label: row.at.slice(0, 10) };case "routine":return row.trigger.kind === "routine"? { key: triggerKey(row.trigger), label: row.trigger.label ?? row.trigger.routineId ?? "unknown" }: { key: "manual", label: "Not from a routine" };+ case "department":+ return { key: `department:${row.section ?? ""}`, label: row.section ?? "" };+default:return { key: `engine:${row.driverKind}`, label: row.driverKind };}@@ -319,7 +330,7 @@ export function csvCell(value: string | number | null): string {}export function usageCsv(rows: UsageRow[], prices: PriceList | null = null): string {- const header = ["time", "bot", "model", "engine", "triggered_by", "input_tokens", "output_tokens", "cached_input_tokens", "cost_usd", "cost_source", ...(prices ? ["billable_usd"] : []), "thread"];+ const header = ["time", "bot", "model", "engine", "triggered_by", "input_tokens", "output_tokens", "cached_input_tokens", "cost_usd", "cost_source", ...(prices ? ["billable_usd"] : []), "thread", "department", "person"];const lines = [header.join(",")];for (const row of rows) {lines.push([@@ -335,6 +346,8 @@ export function usageCsv(rows: UsageRow[], prices: PriceList | null = null): strcostSourceOf(row),...(prices ? [billableFor(row, prices)] : []),row.threadId,+ row.section ?? "",+ personOf(row.trigger) ?? "",].map(csvCell).join(","));}return lines.join("\n") + "\n";diff --git a/src/components/UsageSection.tsx b/src/components/UsageSection.tsxindex 028b8b09cb..75b9017edb 100644--- a/src/components/UsageSection.tsx+++ b/src/components/UsageSection.tsx@@ -15,8 +15,8 @@ import { UsageBudgetCards, type BudgetState } from "./UsageBudget";import { TraceView } from "./usage/TraceView";import { LiveBadge, modelName, StatStrip, totalsStats } from "./usage/TraceWaterfall";-export type UsageGroupBy = "bot" | "model" | "user" | "day" | "engine" | "routine";-const OTHER_GROUPINGS: readonly UsageGroupBy[] = ["model", "user", "day", "engine", "routine"];+export type UsageGroupBy = "bot" | "model" | "user" | "day" | "engine" | "routine" | "department";+const OTHER_GROUPINGS: readonly UsageGroupBy[] = ["model", "user", "department", "day", "engine", "routine"];export interface UsageGroup {key: string;@@ -41,6 +41,7 @@ const GROUP_LABEL_KEYS: Record<UsageGroupBy, LocaleKey> = {day: "usage.history.byDay",engine: "usage.history.byEngine",routine: "usage.history.byRoutine",+ department: "usage.history.byDepartment",};const PERIOD_LABEL_KEYS: Record<UsagePeriod, LocaleKey> = {@@ -55,6 +56,7 @@ const LIVE_REFRESH_MS = 2_000;export function usageGroupLabel(groupBy: UsageGroupBy, group: Pick<UsageGroup, "key" | "label">): string {if (groupBy === "routine") return group.key === "manual" ? t("usage.history.notRoutine") : group.label;+ if (groupBy === "department") return group.label || t("usage.history.noDepartment");if (groupBy !== "user") return group.label;if (group.key === "owner") return t("usage.history.owner");if (group.key === "bot") return t("usage.history.botToBot");diff --git a/src/locales/en.json b/src/locales/en.jsonindex 9f45d97862..d60972ea7f 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -3738,6 +3738,8 @@"usage.history.byDay": "Day","usage.history.byEngine": "Provider","usage.history.byRoutine": "Routine",+ "usage.history.byDepartment": "Department",+ "usage.history.noDepartment": "No department","usage.history.notRoutine": "Not from a routine","usage.history.export": "Export CSV","usage.history.owner": "This computer",