Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(server): expose per-bot usage over RPC (#48)

Leo58825a7d3144
diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts
index c79b241a5..994b2ba68 100644
--- a/apps/server/src/auth/RpcAuthorization.test.ts
+++ b/apps/server/src/auth/RpcAuthorization.test.ts
@@ -42,6 +42,10 @@ describe("RPC authorization scopes", () => {
expect(requiredScopeForRpcMethod(WS_METHODS.memoryMutate)).toBe(AuthOrchestrationOperateScope);
});
+ it("allows bot usage reads without granting orchestration changes", () => {
+ expect(requiredScopeForRpcMethod(WS_METHODS.botUsage)).toBe(AuthOrchestrationReadScope);
+ });
+
it("allows relay status reads without granting relay installation access", () => {
expect(requiredScopeForRpcMethod(WS_METHODS.cloudGetRelayClientStatus)).toBe(
AuthRelayReadScope,
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index 25397b5f8..df669858e 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -67,6 +67,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.memoryImportPreview]: AuthOrchestrationReadScope,
[WS_METHODS.memoryImportApply]: AuthOrchestrationOperateScope,
[WS_METHODS.memoryMutate]: AuthOrchestrationOperateScope,
+ [WS_METHODS.botUsage]: AuthOrchestrationReadScope,
[WS_METHODS.portabilityExport]: AuthOrchestrationReadScope,
[WS_METHODS.portabilityPreviewImport]: AuthOrchestrationReadScope,
[WS_METHODS.portabilityApplyImport]: AuthOrchestrationOperateScope,
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index c6f77b19b..fe8504c78 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -160,6 +160,7 @@ import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClien
import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as UsageService from "./usage/UsageService.ts";
+import { BotUsageLedger, type BotUsageLedgerShape } from "./usage/BotUsageLedger.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
import * as Data from "effect/Data";
@@ -418,6 +419,7 @@ const buildAppUnderTest = (options?: {
analyticsService?: Partial<AnalyticsService.AnalyticsService["Service"]>;
projectionSnapshotQuery?: Partial<ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"]>;
projectionBots?: Partial<ProjectionBots.ProjectionBotRepositoryShape>;
+ botUsageLedger?: Partial<BotUsageLedgerShape>;
checkpointDiffQuery?: Partial<CheckpointDiffQuery.CheckpointDiffQuery["Service"]>;
browserTraceCollector?: Partial<BrowserTraceCollector.BrowserTraceCollector["Service"]>;
serverLifecycleEvents?: Partial<ServerLifecycleEvents.ServerLifecycleEvents["Service"]>;
@@ -808,6 +810,22 @@ const buildAppUnderTest = (options?: {
listAll: () => Effect.succeed([]),
...options?.layers?.projectionBots,
} satisfies ProjectionBots.ProjectionBotRepositoryShape),
+ Layer.mock(BotUsageLedger)({
+ summarize: (botId) =>
+ Effect.succeed({
+ botId,
+ consumedTokens: 0,
+ reservedTokens: 0,
+ measurements: {
+ input: { tokens: 0, unavailableEntries: 0 },
+ output: { tokens: 0, unavailableEntries: 0 },
+ observer: { tokens: 0, unavailableEntries: 0 },
+ reflector: { tokens: 0, unavailableEntries: 0 },
+ },
+ entries: [],
+ }),
+ ...options?.layers?.botUsageLedger,
+ }),
Layer.succeed(ProjectionGroups.ProjectionGroupRepository, {
upsert: () => Effect.void,
getById: () => Effect.succeed(Option.none()),
@@ -4535,6 +4553,87 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+ it.effect("publishes typed per-bot usage with the server-owned cap", () =>
+ Effect.gen(function* () {
+ const botId = BotId.make("bot-usage-rpc");
+ const missingBotId = BotId.make("bot-usage-missing");
+ const summarize = vi.fn<BotUsageLedgerShape["summarize"]>(() =>
+ Effect.succeed({
+ botId,
+ consumedTokens: 1_500,
+ reservedTokens: 32_000,
+ measurements: {
+ input: { tokens: 1_000, unavailableEntries: 1 },
+ output: { tokens: 500, unavailableEntries: 1 },
+ observer: { tokens: 120, unavailableEntries: 0 },
+ reflector: { tokens: 80, unavailableEntries: 1 },
+ },
+ entries: [],
+ }),
+ );
+ const bot = {
+ botId,
+ name: "Usage bot",
+ title: "Usage bot",
+ label: null,
+ description: null,
+ disabledMcpServerIds: [],
+ avatar: { kind: "dither" as const, seed: "usage-bot" },
+ engine: { provider: "codex", model: "gpt-5.6-sol" },
+ sandbox: "local",
+ runtimeMode: "approval-required" as const,
+ usageCap: { unit: "tokens" as const, limit: 64_000 },
+ voiceEnabled: false,
+ groupId: null,
+ archivedAt: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ } satisfies ProjectionBots.ProjectionBot;
+
+ yield* buildAppUnderTest({
+ layers: {
+ projectionBots: {
+ getById: ({ botId: requestedBotId }) =>
+ Effect.succeed(requestedBotId === botId ? Option.some(bot) : Option.none()),
+ },
+ botUsageLedger: { summarize },
+ },
+ });
+
+ const wsUrl = yield* getWsServerUrl("/ws");
+ const result = yield* Effect.scoped(
+ withWsRpcClient(wsUrl, (client) =>
+ Effect.gen(function* () {
+ const usage = yield* client[WS_METHODS.botUsage]({ botId });
+ const missing = yield* client[WS_METHODS.botUsage]({ botId: missingBotId }).pipe(
+ Effect.flip,
+ );
+ return { usage, missing };
+ }),
+ ),
+ );
+
+ assert.deepEqual(result.usage.usageCap, { unit: "tokens", limit: 64_000 });
+ assert.equal(result.usage.consumedTokens, 1_500);
+ assert.equal(result.usage.reservedTokens, 32_000);
+ assert.deepEqual(result.usage.measurements, {
+ input: { tokens: 1_000, unavailableEntries: 1 },
+ output: { tokens: 500, unavailableEntries: 1 },
+ observer: { tokens: 120, unavailableEntries: 0 },
+ reflector: { tokens: 80, unavailableEntries: 1 },
+ });
+ assert.deepEqual(result.usage.estimatedCost, { status: "unavailable", usd: null });
+ assert.deepEqual(result.usage.subscriptionPool, {
+ status: "unavailable",
+ used: null,
+ limit: null,
+ unit: null,
+ });
+ assert.equal(result.missing._tag, "AkeruBotUsageReadError");
+ assert.deepEqual(summarize.mock.calls, [[botId]]);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
it.effect("syncs connector incidents through botInbox.list", () =>
Effect.gen(function* () {
const bot = {
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 2c9b02da6..e93657595 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -10,6 +10,7 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import {
+ AkeruBotUsageReadError,
AkeruMemoryTenantId,
AkeruMemoryUserId,
type AkeruMemoryThreadAccess,
@@ -138,6 +139,7 @@ import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
+import { BotUsageLedger } from "./usage/BotUsageLedger.ts";
import * as UsageService from "./usage/UsageService.ts";
import * as Portability from "./portability.ts";
import * as VoiceCallManager from "./voiceCall/VoiceCallManager.ts";
@@ -474,6 +476,7 @@ const makeWsRpcLayer = (
const voiceCallOwnerId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const projectionBots = yield* ProjectionBots.ProjectionBotRepository;
+ const botUsageLedger = yield* BotUsageLedger;
const projectionGroups = yield* ProjectionGroups.ProjectionGroupRepository;
const entityMemoryRepository = yield* Effect.serviceOption(EntityMemoryRepository);
const memoryCandidates = yield* Effect.serviceOption(MemoryCandidateRepository);
@@ -2325,6 +2328,48 @@ const makeWsRpcLayer = (
}).pipe(Effect.flatMap(({ access, memory }) => memory.mutate(access, input.mutation))),
{ "rpc.aggregate": "memory" },
),
+ [WS_METHODS.botUsage]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.botUsage,
+ Effect.gen(function* () {
+ const bot = yield* projectionBots.getById({ botId: input.botId }).pipe(
+ Effect.mapError(
+ (cause) =>
+ new AkeruBotUsageReadError({
+ botId: input.botId,
+ detail: cause.message,
+ }),
+ ),
+ );
+ if (Option.isNone(bot)) {
+ return yield* new AkeruBotUsageReadError({
+ botId: input.botId,
+ detail: `Bot ${input.botId} was not found.`,
+ });
+ }
+ const summary = yield* botUsageLedger.summarize(input.botId).pipe(
+ Effect.mapError(
+ (cause) =>
+ new AkeruBotUsageReadError({
+ botId: input.botId,
+ detail: cause.message,
+ }),
+ ),
+ );
+ return {
+ ...summary,
+ usageCap: bot.value.usageCap,
+ estimatedCost: { status: "unavailable", usd: null },
+ subscriptionPool: {
+ status: "unavailable",
+ used: null,
+ limit: null,
+ unit: null,
+ },
+ };
+ }),
+ { "rpc.aggregate": "bot" },
+ ),
[WS_METHODS.cloudGetRelayClientStatus]: (_input) =>
observeRpcEffect(WS_METHODS.cloudGetRelayClientStatus, relayClient.resolve, {
"rpc.aggregate": "cloud",
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index 799e06163..8a994a408 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -135,6 +135,10 @@
"types": "./src/state/memory.ts",
"default": "./src/state/memory.ts"
},
+ "./state/bot-usage": {
+ "types": "./src/state/botUsage.ts",
+ "default": "./src/state/botUsage.ts"
+ },
"./state/bot-inbox": {
"types": "./src/state/botInbox.ts",
"default": "./src/state/botInbox.ts"
diff --git a/packages/client-runtime/src/state/botUsage.test.ts b/packages/client-runtime/src/state/botUsage.test.ts
new file mode 100644
index 000000000..3aa45c6ff
--- /dev/null
+++ b/packages/client-runtime/src/state/botUsage.test.ts
@@ -0,0 +1,125 @@
+import { BotId, EnvironmentId, WS_METHODS } from "@t3tools/contracts";
+import { describe, expect, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as SubscriptionRef from "effect/SubscriptionRef";
+import * as Stream from "effect/Stream";
+import { Atom, AtomRegistry } from "effect/unstable/reactivity";
+
+import {
+ AVAILABLE_CONNECTION_STATE,
+ PrimaryConnectionTarget,
+ type PreparedConnection,
+ type SupervisorConnectionState,
+} from "../connection/model.ts";
+import * as EnvironmentRegistry from "../connection/registry.ts";
+import * as EnvironmentSupervisor from "../connection/supervisor.ts";
+import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
+import type { RpcSession } from "../rpc/session.ts";
+import { createBotUsageEnvironmentAtoms } from "./botUsage.ts";
+
+const environmentId = EnvironmentId.make("usage-environment");
+const target = new PrimaryConnectionTarget({
+ environmentId,
+ label: "Usage environment",
+ httpBaseUrl: "https://usage.example.test",
+ wsBaseUrl: "wss://usage.example.test",
+});
+
+describe("bot usage environment atoms", () => {
+ it.effect("keys usage queries by environment and bot and calls bot.usage", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ let requestedBotId: BotId | undefined;
+ let resolveRequest!: () => void;
+ const requested = new Promise<void>((resolve) => {
+ resolveRequest = resolve;
+ });
+ const client = {
+ [WS_METHODS.botUsage]: (input: { readonly botId: BotId }) =>
+ Effect.sync(() => {
+ requestedBotId = input.botId;
+ resolveRequest();
+ return {
+ botId: input.botId,
+ consumedTokens: 0,
+ reservedTokens: 0,
+ measurements: {
+ input: { tokens: 0, unavailableEntries: 0 },
+ output: { tokens: 0, unavailableEntries: 0 },
+ observer: { tokens: 0, unavailableEntries: 0 },
+ reflector: { tokens: 0, unavailableEntries: 0 },
+ },
+ entries: [],
+ usageCap: null,
+ estimatedCost: { status: "unavailable", usd: null },
+ subscriptionPool: {
+ status: "unavailable",
+ used: null,
+ limit: null,
+ unit: null,
+ },
+ };
+ }),
+ } as unknown as WsRpcProtocolClient;
+ const rpcSession: RpcSession = {
+ client,
+ initialConfig: Effect.never,
+ ready: Effect.void,
+ probe: Effect.void,
+ closed: Effect.never,
+ };
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
+ target,
+ state: yield* SubscriptionRef.make<SupervisorConnectionState>({
+ ...AVAILABLE_CONNECTION_STATE,
+ desired: true,
+ network: "online",
+ phase: "connected",
+ attempt: 1,
+ generation: 1,
+ }),
+ session: yield* SubscriptionRef.make(Option.some(rpcSession)),
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
+ connect: Effect.void,
+ disconnect: Effect.void,
+ retryNow: Effect.void,
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
+ const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (_id, effect) =>
+ Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
+ const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
+ _id,
+ stream,
+ ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
+ const registryService = EnvironmentRegistry.EnvironmentRegistry.of({
+ run,
+ followStream,
+ stateChanges: () => SubscriptionRef.changes(supervisor.state),
+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
+ const atoms = createBotUsageEnvironmentAtoms(
+ Atom.runtime(Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, registryService)),
+ );
+ const botId = BotId.make("bot-usage-state");
+ const atom = atoms.summary({ environmentId, input: { botId } });
+ expect(atom).toBe(atoms.summary({ environmentId, input: { botId } }));
+ expect(atom).not.toBe(
+ atoms.summary({ environmentId, input: { botId: BotId.make("bot-usage-other") } }),
+ );
+ expect(atom).not.toBe(
+ atoms.summary({
+ environmentId: EnvironmentId.make("usage-environment-other"),
+ input: { botId },
+ }),
+ );
+ const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) =>
+ Effect.sync(() => value.dispose()),
+ );
+ const unmount = registry.mount(atom);
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
+ yield* Effect.promise(() => requested);
+ expect(requestedBotId).toBe(botId);
+ }),
+ ),
+ );
+});
diff --git a/packages/client-runtime/src/state/botUsage.ts b/packages/client-runtime/src/state/botUsage.ts
new file mode 100644
index 000000000..15b7dd429
--- /dev/null
+++ b/packages/client-runtime/src/state/botUsage.ts
@@ -0,0 +1,18 @@
+import { WS_METHODS } from "@t3tools/contracts";
+import { Atom } from "effect/unstable/reactivity";
+
+import type { EnvironmentRegistry } from "../connection/registry.ts";
+import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
+
+export function createBotUsageEnvironmentAtoms<R, E>(
+ runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
+) {
+ return {
+ summary: createEnvironmentRpcQueryAtomFamily(runtime, {
+ label: "environment-data:bot:usage",
+ tag: WS_METHODS.botUsage,
+ staleTimeMs: 5_000,
+ refreshIntervalMs: 5_000,
+ }),
+ };
+}
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 680f26f2f..14496141a 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -2,6 +2,7 @@ import * as Schema from "effect/Schema";
import * as Rpc from "effect/unstable/rpc/Rpc";
import * as RpcGroup from "effect/unstable/rpc/RpcGroup";
+import { AkeruBotUsageInput, AkeruBotUsageReadError, AkeruBotUsageSnapshot } from "./akeruUsage.ts";
import {
AkeruMemoryArchiveV2,
AkeruMemoryExportInput,
@@ -324,6 +325,7 @@ export const WS_METHODS = {
memoryImportPreview: "memory.importPreview",
memoryImportApply: "memory.importApply",
memoryMutate: "memory.mutate",
+ botUsage: "bot.usage",
portabilityExport: "portability.export",
portabilityPreviewImport: "portability.previewImport",
portabilityApplyImport: "portability.applyImport",
@@ -607,6 +609,12 @@ export const WsMemoryMutateRpc = Rpc.make(WS_METHODS.memoryMutate, {
error: Schema.Union([AkeruMemoryOperationError, EnvironmentAuthorizationError]),
});
+export const WsBotUsageRpc = Rpc.make(WS_METHODS.botUsage, {
+ payload: AkeruBotUsageInput,
+ success: AkeruBotUsageSnapshot,
+ error: Schema.Union([AkeruBotUsageReadError, EnvironmentAuthorizationError]),
+});
+
export const WsPortabilityExportRpc = Rpc.make(WS_METHODS.portabilityExport, {
payload: Schema.Struct({}),
success: PortabilityExportResult,
@@ -1069,6 +1077,7 @@ export const WsRpcGroup = RpcGroup.make(
WsMemoryImportPreviewRpc,
WsMemoryImportApplyRpc,
WsMemoryMutateRpc,
+ WsBotUsageRpc,
WsPortabilityExportRpc,
WsPortabilityPreviewImportRpc,
WsPortabilityApplyImportRpc,